如何在linq中从datatable获取两列数据

4

我目前的情况是:

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

然而,我还需要检索另一列,名为“level”,类型为 int。期望的输出类似于:
var<int,int> ids = ....

或者,既然这只是“Linq-To-Objects”,可以在Linq中选择列表中的多个字段:https://dev59.com/RXM_5IYBdhLWcg3w2XBg - Tim Schmelter
1个回答

7

一种方法是使用匿名类型:

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

这将为您提供一个匿名类型的List<>,因此现在您可以执行以下操作:
var level = ids[0].Level

更新:如果您需要将它们存储在Session中以进行持久化,那么我建议构建一个真正的类型(class),我们称其为Foo。这将更改代码如下:

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

当你需要从Session中获取它们时:

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

Michael,我已经为Session添加了ids,但无法从Session中检索它 - 我尝试了这个: "var ids = (List<Tuple<Int32,Int32>>)Session["ids"]" 但是会出现错误。 - user2906420
@user2906420:你尝试过向“Session”添加“ids”,然后再将其取回吗? - Mike Perrenoud
@user2906420:请查看我的编辑,我试图解决持久性的需求。 - Mike Perrenoud

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接