LINQ help
I have a collection of ints, how can I take the last three that are bigger than 100?
is there a better way than this?
17 Replies
reversing the entire numbers array to take the first (last then) 3 seems kinda ineffecient
I suggest u use for loop reversely
I was curious to try, and got this
Why sort them
seems like a waste of time?
Just traverse in reverse then and pick until you have 3 or reach end (start)
like this?
ForEach
really sucks, dont use itcan you elaborate?
the last
Reverse().ToArray()
seems unnecessary
its a long story, but
1) its slower (iirc)
2) it requires an allocated list (sometimes you dont need to allocate)
var result = numbers.Where(num => num > 100).Reverse().Take(3)
is all you needbut isn't reverse expensive?
sound like O(n) more space
when I only need O(3) more space
linq is lazy, so i doubt it allocates
any way to know for sure?
ask someone in #advanced maybe?
okay
My guess would be to put Reverse first. Linq also has a lot of shortcuts for common collection types and I wouldn't be surprised if Reverse didn't simply enumerate with a decreasing index for arrays.
It's always possible to look into the underlying code of .NET to confirm for yourself, in this case by looking at the body of Reverse
If you don't want to reverse:
Reverse()
indeed completely enumerates the IEnumerable<T>
and copies the result into a new T[]
. It then returns the elements of the newly created array in reverse order.Yeah, we talked about it in #advanced @Joschi
Did they by any chance elaborate on why? Because for
IList<T>
implementations shouldn't it be possible to just yield the content in reverse order using the index?