如何使用LINQ ForEach </int>更改List <int>

时间:2014-01-17 07:38:19

标签: c# linq foreach

我有一个List<int> myInts,想要将所有数字乘以10.我想使用linq(不是foreach循环)。我试过这个,但没有发生任何事情:

List<int> myInts = new List<int>() { 1, 2, 3 };
myInts .ForEach(act => act=act*10);

.ForEach(...)部分我需要注意什么?是的,我想在某种程度上使用ForEach。

可能很简单,但我看不清楚,我很抱歉。谢谢大家!

8 个答案:

答案 0 :(得分:5)

这会创建一个新的List实例。

myInts = myInts.Select(p=>p*10).ToList();

答案 1 :(得分:3)

“没有任何反应”,因为重新分配给本地变量(act)在调用者(ForEach)中无效 - C#是Call By Value(除了对于ref / out参数)。

要修改列表到位,只需在索引上使用标准for-each(我发现副作用意图的可读性和前期):

var myInts = new List<int>() { 1, 2, 3 };
for (var i = 0; i < myInts.Count; i++) {
    myInts[i] = myInts[i] * 10;
}

要执行操作并创建新的列表/序列(可以重新分配给同一个变量),请参阅IEnumerable.Select这是map转换。

答案 2 :(得分:3)

另一个更简单的解决方案:

list = list.ConvertAll(i => i * 10);

答案 3 :(得分:2)

来自MSDN文档:

Modifying the underlying collection in the body of the Action<T> delegate 
is not supported and causes undefined behavior.

因此,您需要将您的exisistin列表投影到新的列表中,或者如果必须“就地”修改列表,则需要使用for循环

此致

答案 4 :(得分:1)

发生的事情是你得到了一个int值的副本到你的lambda,这样你就无法改变'external'int。

如何投射新名单?

List<int> myInts = new List<int>() { 1, 2, 3 };
myInts = myInts.Select(act => act*10).ToList();

答案 5 :(得分:1)

使用.Select.ConvertAll是很好的解决方案。

但我的目的是让“ForEach”返回一个改动列表。 我发现,通过msdn文档,这不可能,因为ForEach是void类型,没有返回类型。

如果我的列表中有对象而不是整数,则此类操作有效。然后我就可以使用“void”方法来改变对象的属性。

答案 6 :(得分:0)

你的意思是这样吗?

     List<int> _tempList = new List<int>();
     myInts.ToList().ForEach(x => _tempList.Add(x * 10));

答案 7 :(得分:0)

试试这个:

Enumerable.Range(0, myInts.Count).ToList().ForEach(i => myInts[i] = myInts[i] * 10);