How to get 2 columns from datatable in linq

I currently have:

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

However, I also need to find another column, name: "level" of type int. waiting for the output something like:

var<int,int> ids = ....
+4
source share
1 answer

One approach will be anonymous:

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

This will give you List<>this anonymous type, so now you can do something like this:

var level = ids[0].Level

UPDATE: if you need to save them in Sessionto save, I would recommend creating a real type ( class), call it Foofor this example. This will 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 infer them from Session:

var ids = (List<Foo>)Session["ids"];
+6
source

Source: https://habr.com/ru/post/1525234/


All Articles