C# Convert DataTable to List in C#
In C#, a DataTable is an object that represents tabular data. Sometimes, we need to convert this DataTable to a List of objects to make it easier to work with. In this tutorial, we'll discuss how to convert a DataTable to a List in C#.
Syntax
The syntax for converting a DataTable to a List in C# is as follows:
List<MyClass> myObjects = dt.AsEnumerable()
.Select(row => new MyClass {
Prop1 = row.Field<string>("Column1"),
Prop2 = row.Field<int>("Column2"),
Prop3 = row.Field<bool>("Column3")
})
.ToList();
First, we use the AsEnumerable() method to treat the DataTable as if it were a collection of rows. Then, we use the Select() method to create a new object of type MyClass for each DataRow in the DataTable. Finally, we use the ToList() method to convert the collection to a List
Example
Let's say we have a DataTable called "myTable" with three columns: "Name", "Age", and "IsMarried". Here's how we can convert it to a List of objects:
public class Person {
public string Name { get; set; }
public int Age { get; set; }
public bool IsMarried { get; set; }
}
List<Person> people = myTable.AsEnumerable()
.Select(row => new Person {
Name = row.Field<string>("Name"),
Age = row.Field<int>("Age"),
IsMarried = row.Field<bool>("IsMarried")
})
.ToList();
Now, we can work with the List of Person objects as we would any other List in C#.
Output
There is no output generated from this code, as it simply converts a DataTable to a List of objects.
Explanation
In the example above, we converted a DataTable to a List of Person objects. We used the AsEnumerable() method to obtain the rows in the DataTable as an IEnumerable, and then used the Select() method to transform each DataRow into a Person object. Finally, we used the ToList() method to convert the IEnumerable
Use
Converting a DataTable to a List of objects can be useful when we need to perform operations on the data as a collection of objects, rather than manipulating it as a DataSet.
Important Points
- The columns in the DataTable must have the same names and data types as the properties defined in the class.
- Properties must be settable in order for this method to work.
- If your column name is different than the property name, use the Field<> extension method to retrieve the data from the column.
Summary
In this tutorial, we discussed how to convert a DataTable to a List of objects in C#. We covered the syntax, example, output, explanation, use, and important points of this conversion. With this knowledge, you can now easily manipulate a DataTable as a collection of objects in your C# code.