CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Monday, May 02, 2011

DataTable to Generic List Conversion

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; }
}
}

Post a Comment