C#linq过滤器整数数组

时间:2016-07-27 18:24:50

标签: c# linq

给出一系列整数:

int[] testInt = new int[] { 2, 3, 1, 0, 0 };

如何返回每个元素符合条件的整数数组?

要返回所有元素大于零,我已尝试

int[] temp = testInt.Where(i => testInt[i] > 0).ToArray();

...但这只会返回一个包含4个2, 1, 0, 0元素的索引。

3 个答案:

答案 0 :(得分:6)

i是数组元素:

int[] temp = testInt.Where(i => i > 0).ToArray();

Where接受一个函数(Func<int, bool>),然后Where遍历数组的每个元素并检查条件是否为真并产生该元素。当您编写i =>时,i是数组中的元素。好像你写道:

foreach(var i in  temp)
{
   if( i > 0)
      // take that i
}

答案 1 :(得分:4)

您传递lambda表达式(样本上的i)的元素,它是集合中的元素,在这种情况下是int值。样本:

int[] temp = testInt.Where(i => i > 0).ToArray();

您也可以通过索引传递lambda表达式,该表达式获取元素的索引。这不是一个好的实践,使用您在示波器上已有的元素是最佳选择,但对于其他示例,您可以使用索引。样本:

int[] temp = testInt.Where((item, index) => testInt[index] > 0).ToArray();

答案 2 :(得分:0)

int[] temp = testInt.Where(p=>p>0).ToArray()