Monday, 4 February 2013

Convert DataTable to IEnumerable for LINQ processing

[Test]
public void TestDataTableToEnumeration()
{
    var dt = new DataTable();
    dt.Columns.Add("Id", typeof (int));
    dt.Columns.Add("Name", typeof (string));
    dt.Columns.Add("Value", typeof (double));
    for (int i = 0; i < 5; i++)
    {
        var row = dt.NewRow();
        row["Id"] = i;
        row["Name"] = "Name" + i;
        row["Value"] = i + 0.1d;
        dt.Rows.Add(row);
    }
    var data = dt.AsEnumerable().Select(row =>
        new
            {
                Id = (int) row["Id"],
                Name = (string) row["Name"],
                Value = (double) row["Value"]
            }).Where(x => x.Id < 3);
    foreach (var row in data)
    {
        Console.WriteLine("{0},{1},{2}", row.Id, row.Name, row.Value);
    }
}