Search code examples
c#linqlinq-to-dataset

Simplify my C# Linq statement?


class :

class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

List

List<Foo> lst = new List<Foo>();

Datatable :

 DataTable dt = GetFromDb ()....

I want to fill lst with records from dt.

I've managed doing :

Array.ForEach(dt.AsEnumerable().ToArray(), y = > lst.Add(new Foo()
{
    Id = int.Parse(y["id"].ToString()), Name = y["name"].ToString()
}));

question :

  1. Can't I do something else like dt.AsEnumerable().Select(_ => fill lst ) ?

I know that part of the select signature (in this case ) is Func<datarow,void> which wont compile

But still , is there any other way of doing this besides the ugly way of mine ?


Solution

  • Using LINQ to DataSet:

    var foos = from row in dt.AsEnumerable()
               select new Foo()
               {
                  Id = row.Field<int>("id"),
                  Name = row.Field<string>("name")
               };
    
    // create a new list
    List<Foo> lst = foos.ToList();
    
    // update: add items to an exisiting list
    fooList.AddRange(foos);