0

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.

0

3 Answers 3

6

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
}
Sign up to request clarification or add additional context in comments.

Comments

4

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();

2 Comments

The second example here is good for pointing towards the situation where each index meets a criteria, such as int[] temp = testInt.Where((item, index) => index < testInt.Length - 1).ToArray(); to copy all but the last element. The question involves criteria with elements, but I think this answer gets bonus points because it points how to deal with criteria with indexes and elements.
There are a lot of methods on Linq specification that allows you to take the element and its index. I hope help you anyway. :)
0
int[] temp = testInt.Where(p=>p>0).ToArray()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.