This blog is moved to
http://amalhashim.wordpress.com

Monday, May 2, 2011

DataTable to GenericList | C# and LINQ

Programming Microsoft® LINQ in Microsoft .NET Framework 4 
using System;
using System.Data;

namespace ConsoleApplication1
{
class Program
{

static void Main(string[] args)
{
DataTable table = new DataTable
{
Columns = {
{"Id", typeof(int)},
{"Name", typeof(string)}
}
};

table.Rows.Add(1, "Amal");
table.Rows.Add(1, "Fousiya");
table.Rows.Add(1, "Munna");
table.Rows.Add(1, "Hussain");         

var listOfEmployees = from row in table.AsEnumerable()
select new Employee
{
Id = row.Field<int>("Id"),
Name = row.Field<String>("Name")
};

foreach (Employee emp in listOfEmployees)
{
Console.WriteLine("{0}   {1}", emp.Id, emp.Name);
}
}
}

class Employee
{
public int Id { get; set; }
public String Name { get; set; }
}
}

No comments: