与 IEnumerable 列表一起使用的聚合方法
当不同类型在其构造函数中接受前一种类型时,是否有一种方法可以将例如字符串的 IEnumerable 列表“转换”(返回)为不同类型的 IEnumerable 列表?
例如,DataTable.Columns.AddRange()
方法仅接受列列表。有没有办法通过使用 LINQ 或某种聚合函数提供 string
列表来返回 DataColumn
列表?我想代码大致会执行以下操作,但在一行中:
var columnList = new List<DataColumn>();
foreach (var item in myStringList)
{
columnList.Add(item);
}
return columnList;
同样,是否有一种聚合方法将获取一个列表并针对特定方法运行其每个成员?例如,我正在寻找一种单行方法来执行以下类似的 foreach
循环:
foreach (var item in myStringList)
{
myDataTable.Columns.Add(item);
}
显然,我正在寻找实际上并不依赖于数据列或字符串的通用答案。
Is there a way to "convert" (return) an IEnumerable list of, e.g., strings to an IEnumerable list of a different type when that different type accepts the former type in its constructor?
For example, the DataTable.Columns.AddRange()
method accepts only lists of columns. Is there a way to return a DataColumn
list by offering a string
list using LINQ or some sort of aggregate function? I imagine the code would roughly do the following, but in one line:
var columnList = new List<DataColumn>();
foreach (var item in myStringList)
{
columnList.Add(item);
}
return columnList;
Likewise, is there an aggregate method that will take a list and run each of its members against a specific method? For example, I am looking for a one line way to perform the following similar foreach
loop:
foreach (var item in myStringList)
{
myDataTable.Columns.Add(item);
}
Obviously, I am looking for generic answers that are not actually dependent on data columns or strings.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以编写
这些方法由
List
类定义。如果您有任意
IEnumerable
,则可以使用 LINQ:You can write
These methods are defined by th
List<T>
class.If you have an arbitrary
IEnumerable<T>
, you can use LINQ:调用 Enumerable.Aggregate
也就是说,foreach 语句更好。
Call Enumerable.Aggregate
That said, foreach statement is better.
是的,事实上,尽管并非所有这些都是特定于 LINQ 的。 ForEach 只是一个 List 方法。对于您的两个示例:
ForEach 方法采用一个操作,并允许您对每个项目执行一些逻辑。因此,如果你想进行转换,与 select 结合起来就很容易了:
Yes, in fact, although not all of them are LINQ specific. ForEach is just a List method. For your two examples:
The ForEach method takes an Action and lets you perform some logic on each item. So if you want to do transformations, it's easy enough combining with select:
myStringList.ForEach(item => myDataTable.Columns.Add(item));
编辑:那不是 Linq。抱歉,我的错误。
myStringList.ForEach(item => myDataTable.Columns.Add(item));
EDIT: that's not Linq. Sorry, my mistake.