FindLast on IEnumerable

I would like to call FindLastin a collection that implements IEnumerable, but FindLastis only available for List. What is the best solution?

+5
source share
5 answers

Equivalent:

var last = list.FindLast(predicate);

is an

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

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

In fact, “Where ()” is part of the “Search”, and “Last ()” is the last part of “FindLast”, respectively. Similarly, it FindFirst(predicate)will display on sequence.Where(predicate).FirstOrDefault(), but it FindAll(predicate)will sequence.Where(predicate).

+8
source

As with LINQ-to-Objects:

var item = data.LastOrDefault(x=>x.Whatever == "abc"); // etc

# 2, :

using System;
using System.Collections.Generic;
static class Program {
    static void Main() {
        int[] data = { 1, 2, 3, 4, 5, 6 };

        int lastOdd = SequenceUtil.Last<int>(
            data, delegate(int i) { return (i % 2) == 1; });
    }    
}
static class SequenceUtil {
    public static T Last<T>(IEnumerable<T> data, Predicate<T> predicate) {
        T last = default(T);
        foreach (T item in data) {
            if (predicate(item)) last = item;
        }
        return last;
    }
}
+4

, List < > constructor.

List<MyClass> myList = new List<MyClass>(MyCol);
myList.FindLast....
+1

Use the Last () extension method, which is in the System.Linq namespace.

0
source

Your question is invalid because the collection does not have the last item. A list of a more specialized collection, which has a complete order, is a list. A more specialized collection that does not have an order is a dictionary.

0
source

All Articles