如何在c#中替换列表中的多个值?
c#
如果我有一个包含 100 个整数的列表,如何在不使用循环的情况下将索引 20 到 50 处的值分配给长度为 31 的列表中的一组不同的值?来自 python,这很容易在没有循环的情况下完成,但我不确定是否可以在 c# 中完成。
回答
使用 LINQ,即“在我的代码中不使用循环”,您可以:
hundredInts.Take(19).Concat(thirtyoneInts).Concat(hundredInts.Skip(50));
(如果您希望它作为列表或数组等返回,则在其末尾进行相关的 ToXXX 调用)
也许:
hundredInts.Select((n, i) => (i < 20 || i > 50) ? n : thirtyOneInts[i-20])
或者内置的东西:
hundredInts.RemoveRange(20, 31).InsertRange(20, thirtyOneInts);
- I'd really refrain from telling someone that doesn't know c# that LINQ is a solution for this. People get the wrong idea and look at me like I was crazy when I explain them that linq doesn't do magic and it *does* use loops