简体   繁体   English

如何使用LINQ将id列表作为int

[英]How do I get list of id's as int using LINQ

I have a DataTable, say pdt, in my code. 我的代码中有一个DataTable,比如pdt。 I just want to select all table["id"] and populate then in an integer array. 我只想选择所有table["id"]并在整数数组中填充。

I can go ahead with a foreach but I am trying to learn Lambda expressions. 我可以继续使用foreach但我正在尝试学习Lambda表达式。 I can't figure out how to deal with this. 我无法弄清楚如何处理这个问题。

I have tried 我试过了

List<int> Ids = pdt.Select(row => row["Id"]; return Convert.ToInt32(r));

and

int[] Ids = pdt.Select(row => row["Id"]);

but nothing seems to work. 但似乎没什么用。 I am pretty sure this is a basic question, help out a newbie please. 我很确定这是一个基本问题,请帮助新手。

If you want an array, you need to use the ToArray() extension method... but you also want to use the DataTableExtensions.AsEnumerable() extension method to make the data table strongly typed in terms of a DataRow sequence: 如果你想要一个数组,你需要使用ToArray()扩展方法...但是你想使用DataTableExtensions.AsEnumerable()扩展方法来根据DataRow序列强类型化数据表:

int[] ids = pdt.AsEnumerable()
               .Select(r => (int) r["Id"])
               .ToArray();

EDIT: As noted in abatishchev's answer, an alternative to the explicit cast here would be to use the Field<T> extension method (in DataRowExtenions ): 编辑:正如abatishchev的回答所述,这里显式转换的替代方法是使用Field<T>扩展方法(在DataRowExtenions ):

int[] ids = pdt.AsEnumerable()
               .Select(r => r.Field<int>("Id"))
               .ToArray();

使用类型安全的电话:

r.Field<string>("Id")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM