Reputation: 89
I've tried combining multiple other questions/answers but without success.
I have a array containing integers varying from 0 through 10. Now I need an array with only the integers higher then e.g. 8.
How can I filter or create a subarray which will contain only those integers?
Upvotes: 0
Views: 1106
Reputation: 1500245
Sounds like you want LINQ. For example:
int[] largeIntegers = allIntegers.Where(x => x > 8).ToArray();
Depending on what you need to do though, you may not really need the ToArray
call. For example:
IEnumerable<int> largeIntegers = allIntegers.Where(x => x > 8);
foreach (int value in largeIntegers)
{
...
}
LINQ is capable of much more than filtering though - I would strongly advise you to learn about it properly - there's a huge amount of material on the net about it. I have a whole blog series about LINQ to Objects, for example - but LINQ goes beyond just in-process queries too.
You might also want to read Eric Lippert's blog post "arrays considered somewhat harmful" for reasons to prefer other collections over arrays in many cases.
Another alternative would be to use Array.FindAll
:
int[] largeIntegers = Array.FindAll(allIntegers, x => x > 8);
... but this then really ties you into arrays. LINQ is more general.
Upvotes: 6
Reputation: 39610
You can use LINQ for filtering your array:
var filteredArray = existingArray.Where(x => x > 8).ToArray();
Upvotes: 3
Reputation: 5575
You can use LinQ:
(from num in array where num > 8 select num).ToArray();
Also you can try:
var filteredArray = yourArray.Where(c => c >8);
Upvotes: 0