.net 代替。。。if数组迭代

.net 代替。。。if数组迭代,.net,python,arrays,loops,iteration,.net,Python,Arrays,Loops,Iteration,我喜欢Python中的列表理解,因为它们简洁地表示列表的转换 然而,在其他语言中,我经常发现自己写的东西大致如下: foreach (int x in intArray) if (x > 3) //generic condition on x x++ //do other processing 这个例子是在C#中,我觉得LINQ可以帮助解决这个问题,但是有没有一些通用的编程结构可以取代这个稍微不够优雅的解决方案?也许我没有考虑数据结构?取决于语言和您需要做的事情,许

我喜欢Python中的列表理解,因为它们简洁地表示列表的转换

然而,在其他语言中,我经常发现自己写的东西大致如下:

foreach (int x in intArray)
  if (x > 3) //generic condition on x
    x++ 
    //do other processing

这个例子是在C#中,我觉得LINQ可以帮助解决这个问题,但是有没有一些通用的编程结构可以取代这个稍微不够优雅的解决方案?也许我没有考虑数据结构?

取决于语言和您需要做的事情,许多语言中称之为“地图”的“地图”可能就是您想要的。我不知道C#,但根据page,.net2.0调用map“ConvertAll”

“map”的含义非常简单——获取一个列表,对其中的每个元素应用一个函数,返回一个新列表。您还可能正在寻找“过滤器”,它将为您提供满足另一个列表中谓词的项目列表。

在Ruby中:

intArray.select { |x| x > 3 }.each do |x|
  # do other processing
end
或者,如果“其他处理”是短的一行:

intArray.select { |x| x > 3 }.each { |x| something_that_uses x }
最后,如果要返回一个新数组,其中包含对大于3的元素的处理结果:

intArray.select { |x| x > 3 }.map { |x| do_something_to x }
在Python中,您有,这可以满足您的需要:

map(lambda x: foo(x + 1) filter(lambda x: x > 3, intArray))
在一句简单的话中,还有两种方法可以做到:

[f(x + 1) for x in intArray if x > 3]
在C#中,您可以对IEnumerable中的任何对象应用选择性处理,如下所示:

intArray.Where(i => i > 3).ConvertAll();
DoStuff(intArray.Where(i => i 3));

Etc..

原始
foreach
循环中的增量不会影响数组的内容,唯一的方法仍然是
for
循环:

for(int i = 0; i < intArray.Length; ++i)
{
    if(intArray[i] > 3) ++intArray[i];
}
如某些其他答案所示,使用
(或等效项),将从结果序列中排除任何小于或等于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
块,不过对于方法调用以外的任何调用,我都坚持使用
ForEach

intArray.ForEach(i => DoSomething(i));
intArray.ForEach(i => DoSomething(i));
map(lambda x: test(x + 1) filter(lambda x: x > 3, arr))