具有索引的List< ForEach [英] List<T>.ForEach with index
问题描述
我正在尝试查找与以下代码等效的LINQ:
I'm trying to find the LINQ equivalent of the following code:
NameValueCollection nvc = new NameValueCollection();
List<BusinessLogic.Donation> donations = new List<BusinessLogic.Donation>();
donations.Add(new BusinessLogic.Donation(0, "", "", "");
donations.Add(new BusinessLogic.Donation(0, "", "", "");
donations.Add(new BusinessLogic.Donation(0, "", "", "");
for(var i = 0; i < donations.Count(); i++)
{
// NOTE: item_number_ + i - I need to be able to do this
nvc.Add("item_number_" + i, donations[i].AccountName);
}
我希望我可以使用类似的东西:
I was hoping I could use something like:
NameValueCollection nvc = new NameValueCollection();
List<BusinessLogic.Donation> donations = new List<BusinessLogic.Donation>();
donations.Add(new BusinessLogic.Donation(0, "", "", "");
donations.Add(new BusinessLogic.Donation(0, "", "", "");
donations.Add(new BusinessLogic.Donation(0, "", "", "");
donations.ForEach(x => nvc.Add("item_name_" + ??, x.AccountName);
但是我还没有找到一种确定循环正在进行的迭代的方法.任何帮助将不胜感激!
But I've not found a way to determine which iteration the loop is on. Any help would be appreciated!
推荐答案
LINQ没有ForEach
方法,这是有充分理由的. LINQ用于执行查询.它旨在从某些数据源获取信息.它不是为更改数据源而设计的. LINQ查询不应引起副作用,这正是您在这里所做的.
LINQ doesn't have a ForEach
method, and for good reason. LINQ is for performing queries. It is designed to get information from some data source. It is not designed to mutate data sources. LINQ queries shouldn't cause side effects, which is exactly what you're doing here.
List
类确实具有一个ForEach
方法,这就是您正在使用的方法.因为它实际上不在System.Linq
命名空间中,所以从技术上讲它不是LINQ的一部分.
The List
class does have a ForEach
method, which is what you are using. Because it's not actually in the System.Linq
namespace it's not technically a part of LINQ.
问题中的for
循环没有任何问题. (从良好实践的角度出发)尝试以您尝试的方式进行更改是错误的.
There is nothing wrong with the for
loop in your question. It would be wrong (from a good practice perspective) to try to change it in the way that you're trying to.
此处是一个更详细地讨论此问题的链接.
Here is a link that discusses the matter in more detail.
现在,如果您想忽略该建议并仍然使用ForEach
方法,那么编写提供该操作索引的方法并不难:
Now, if you want to ignore that advice and use a ForEach
method anyway, it's not hard to write one that provides an index to the action:
public static void ForEach<T>(this IEnumerable<T> sequence, Action<int, T> action)
{
// argument null checking omitted
int i = 0;
foreach (T item in sequence)
{
action(i, item);
i++;
}
}
这篇关于具有索引的List< ForEach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!