C# – FindLast on IEnumerable

c++ienumerableilist

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

Best Solution

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).