Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get 2 columns from datatable in linq [duplicate]

Tags:

c#

linq

I currently have:

var ids = dt.AsEnumerable().Select(x => (int)x["Id"]).ToList();

However I also need to retreive another column, name: "level" of type int also. expecting output something like:

var<int,int> ids = ....
like image 381
user2906420 Avatar asked Mar 21 '23 16:03

user2906420


1 Answers

One approach would be an anonymous type:

var ids = dt.AsEnumerable().Select(x => new
{
    Id = (int)x["Id"],
    Level = (int)x["level"]
}).ToList();

This will give you a List<> of that anonymous type, so now you could do something like this:

var level = ids[0].Level

UPDATE: if you're going to have to store them in Session for persistence then I'd recommend building a real type (class), let's call it Foo for this example. That would change the code to:

var ids = dt.AsEnumerable().Select(x => new Foo
{
    Id = (int)x["Id"],
    Level = (int)x["level"]
}).ToList();

Then when you need to get them out of Session:

var ids = (List<Foo>)Session["ids"];
like image 187
Mike Perrenoud Avatar answered Mar 23 '23 05:03

Mike Perrenoud