Converting DataRow to Object in C#
Let's now explore how to convert from DataRow to custom C# objects.
using System;
using System.Collections.Generic;
using System.Data;
class Program
{
static void Main(string[] args)
{
// Get Sample DataTable
DataTable dataTable = GetSampleDataTable();
// Convert DataRow objects to Car objects
List<Car> cars = new List<Car>();
foreach (DataRow row in dataTable.Rows)
{
Car car = ConvertDataRowToCar(row);
cars.Add(car);
}
// Output Car objects
foreach (Car car in cars)
{
Console.WriteLine(car.ToString());
}
Console.ReadKey();
}
static Car ConvertDataRowToCar(DataRow row)
{
// Convert DataRow to Car object
Car car = new Car
{
Id = Convert.ToInt32(row["Id"]),
Make = row["Make"].ToString(),
Model = row["Model"].ToString(),
Year = Convert.ToInt32(row["Year"])
};
return car;
}
static DataTable GetSampleDataTable()
{
// Create a DataTable and populate it with sample data
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Id", typeof(int));
dataTable.Columns.Add("Make", typeof(string));
dataTable.Columns.Add("Model", typeof(string));
dataTable.Columns.Add("Year", typeof(int));
// Adding sample rows
dataTable.Rows.Add(1, "Toyota", "Camry", 2020);
dataTable.Rows.Add(2, "Honda", "Civic", 2019);
dataTable.Rows.Add(3, "Ford", "Mustang", 2024);
return dataTable;
}
}
class Car
{
// Properties representing the structure of the Car object
public int Id { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public int Year { get; set; }
public override string ToString()
{
return $"Id: {Id}, Make: {Make}, Model: {Model}, Year: {Year}";
}
}
Car
Class represents a car with Id
, Make
, Model
, and Year
properties. ConvertDataRowToCar
Method converts a DataRow
into a Car
object by mapping the columns of the DataRow
to the properties of the Car
. GetSampleDataTable
Method creates a DataTable
and populates it with sample car data. Main
Method retrieves the DataTable
, converts each DataRow
to a Car
object, and prints out the details of each car.
Output:
Id: 1, Make: Toyota, Model: Camry, Year: 2020
Id: 2, Make: Honda, Model: Civic, Year: 2019
Id: 3, Make: Ford, Model: Mustang, Year: 2024
Comments (0)