我喜欢 Python 中的列表理解,因为它们简洁地表示列表的转换。
然而,在其他语言中,我经常发现自己在写一些类似这样的东西:
foreach (int x in intArray)
if (x > 3) //generic condition on x
x++
//do other processing
这个例子是在 C# 中,我的印象是 LINQ 可以帮助解决这个问题,但是是否有一些通用的编程结构可以取代这个稍微不那么优雅的解决方案?也许是我没有考虑的数据结构?
最佳答案
原始 foreach
循环中的增量不会影响数组的内容,唯一的方法仍然是 for
循环:
for(int i = 0; i < intArray.Length; ++i)
{
if(intArray[i] > 3) ++intArray[i];
}
Linq 无意修改现有的集合或序列。它基于现有序列创建新序列。可以使用 Linq 实现上述代码,尽管这有点违背其目的:
var newArray1 = from i in intArray select ((i > 3) ? (i + 1) : (i));
var newArray2 = intArray.Select(i => (i > 3) ? (i + 1) : (i));
如其他一些答案所示,使用 where
(或等效项)将从结果序列中排除任何小于或等于 3 的值。
var intArray = new int[] { 10, 1, 20, 2 };
var newArray = from i in intArray where i > 3 select i + 1;
// newArray == { 11, 21 }
数组上有一个 ForEach
方法,它允许您使用 lambda 函数而不是 foreach
block ,尽管除了方法调用之外,我会坚持使用 foreach
。
intArray.ForEach(i => DoSomething(i));
关于.net - 替换 for...if 数组迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13396/