我使用以下代码逐步完成了IEnumerable。
IEnumerable<Thing> things = ...;
foreach (Thing thing in things)
thing = method(thing);
编译器不同意它,因为我指的是迭代变量。当然,我打算改为影响列表中的基础对象。我怎么做?
现在,我使用了一个数值迭代来解决问题,但是这里有两个问题。一方面,恕我直言编码不好。除此之外,它要求我将我的东西从IEnumerable更改为IList(或者我应该使用List ?!),当事情变大时,它会咬在我的下背部。
//List<Thing> things = ...;
IList<Thing> things = ...;
for (int i = 0; i < things.Count(); i++)
things[i] = method(things[i]);
最佳答案
您可以使用Linq投影序列:
var transformedThings = things.Select(t => method(t));
关于c# - 如何在foreach中引用实际元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15476516/