Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindLast on IEnumerable

I would like to call FindLast on a collection which implements IEnumerable, but FindLast is only available for List. What is the best solution?

like image 979
JoelFan Avatar asked Jan 12 '09 15:01

JoelFan


People also ask

How do I access items in IEnumerable?

var item = eLevelData. ElementAt(index); If your collection is typed as IEnumerable instead of IEnumerable<T> you'll need to use the Cast extension method before you can call ElementAt e.g.


1 Answers

The equivalent to:

var last = list.FindLast(predicate);

is

var last = sequence.Where(predicate).LastOrDefault();

(The latter will have to check all items in the sequence, however...)

Effectively the "Where()" is the Find part, and the "Last()" is the Last part of "FindLast" respectively. Similarly, FindFirst(predicate) would be map to sequence.Where(predicate).FirstOrDefault() and FindAll(predicate) would be sequence.Where(predicate).

like image 170
Jon Skeet Avatar answered Nov 14 '22 21:11

Jon Skeet