Hello Friends, In this article I will show you a small code example to convert DataTable to List or Array in C# code example.
Convert DataTable to List or Array
This is the problem we come across many scenarios where we have to convert a DataTable to some custom array.
Below is sample to code to create a datatable. In practical scenario some data source like SQL will generate the DataTable.
DataTable dtStudents = new DataTable(); dtStudents.Columns.Add("ID", typeof(int)); dtStudents.Columns.Add("FirstName", typeof(String)); dtStudents.Columns.Add("LastName", typeof(String)); dtStudents.Columns.Add("Marks", typeof(int)); string[] fName = { "Vikram", "Martin", "Tim", "Cook", "Larry" }; string[] lName = { "Chaudhary", "George", "Jobs", "Steve", "Page" }; Random random = new Random(); for (int i = 0; i < 5; i++) { DataRow dtRow = dtStudents.NewRow(); dtRow["ID"] = i + 1; dtRow["FirstName"] = fName[i]; dtRow["LastName"] = lName[i]; dtRow["Marks"] = random.Next(400, 500); dtStudents.Rows.Add(dtRow); } IList<string> studentNa
Convert DataTable to String Array
This is a simple use case. If you want to get an string array of the full name. Below code will help you to get it.
The below code concatenates the First Name and Last Name. And return a string array of full name.
IList<string> studentNames = dtStudents.AsEnumerable().Select(item => string.Format("{0}, {1}", item["firstName"], item["lastName"])).ToList();
Convert DataTable to Custom class Array
The below code snippet is for an example to convert DataTable to custom class. Suppose you want your DataTable structure to FullName and Percentage as class properties.
var studentNamesWithPercentage = dtStudents.AsEnumerable().Select(item => new { fullName = string.Format("{0}, {1}", item["firstName"], item["lastName"]) , Percentage = (Convert.ToInt32(item["Marks"])/100) * 100 }).ToList() ;
As you can see in both of the above examples I am using Anonymous types. And this is a very good use case for Anonymous types in C#.
Concluding from both of the above examples we have to use AsEnumerable() extension method for the DataTable. This is due to the reason that we cannot enumerate the DataTable directly. The other option would have been to Enumerate on the rows collection.
Leave a Reply