Aaron Thomas
Aaron Thomas

Reputation: 5281

C# linq filter array of ints

Given an array of ints:

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

How can I return an array of ints where each element meets a criteria?

To return all elements are greater than zero, I've tried

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

...but this only returns an index with 4 elements of 2, 1, 0, 0.

Upvotes: 0

Views: 5562

Answers (3)

marius
marius

Reputation: 349

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

Upvotes: 0

Felipe Oriani
Felipe Oriani

Reputation: 38608

The element you pass on the lambda expression (i on the sample), it is your element on the collection, in the case, the int value. For sample:

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

You also can use by index passing the lambda expression which takes the index on the element. It's not a good pratice, using the element you already have on the scope is the best choice, but for other samples, you could use the index. For sample:

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

Upvotes: 4

Zein Makki
Zein Makki

Reputation: 30022

i is the array element:

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

Where accepts a function (Func<int, bool>) then Where iterates through each element of the array and checks if the condition is true and yields that element. When you write i => the i is the element inside the array. As if you wrote:

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

Upvotes: 6

Related Questions