.net - 替换 for...if 数组迭代

标签 .net python arrays loops iteration

我喜欢 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/

相关文章:

python - 根据轮廓颜色给点上色

python - 与 numpy.eye 相比,使用 numpy.identity 有什么优势?

c# - Windows 操作系统中的 Outlook 签名文件夹

c# - 如何将程序集引用添加到加载的程序集?

python - Python中字典操作的别名

java - 从另一个 JTextField 读取字符串后修改 JTextField

java - 迭代 strings.xml 中存储的字符串

java - 为什么每次读取文件的一行时我的对象都没有存储到数组中? java

c# - 从组合框的选定索引更改的源中获取其他值

c# - 如果我在 MongoDB 上使用 LINQ,为什么会失去性能?