Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 383
Royi Namir Avatar asked Nov 17 '25 20:11

Royi Namir


1 Answers

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);
like image 185
Lucas Avatar answered Nov 19 '25 08:11

Lucas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!