DataTable to Generic List Conversion
Posted
on Microsoft .NET Support Team
See other posts from Microsoft .NET Support Team
Published on Sun, 01 May 2011 19:21:00 +0000
Indexed on
2011/06/20
16:34 UTC
Read the original article
Hit count: 196
Filed under:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable table = new DataTable
{
Columns = {
{"Number", typeof(int)},
{"Name", typeof(string)}
}
};
//Just adding few test rows to datatable.
for (int i = 1; i <= 5; i++)
{
table.Rows.Add(i, "Name" + i);
}
var returnList = from row in table.AsEnumerable()
select new MyObject
{
Number = row.Field<int>("Number"),
Name = row.Field<String>("Name")
};
//Displaying converted collection
foreach (MyObject item in returnList)
{
Console.WriteLine("{0}\t{1}", item.Number, item.Name);
}
}
}
class MyObject
{
public int Number { get; set; }
public String Name { get; set; }
}
}
© Microsoft .NET Support Team or respective owner