IEnumerable上的FindLast

Joe*_*Fan 5 c# ienumerable ilist

我想调用FindLast一个实现的集合IEnumerable,但FindLast仅适用于List.什么是最好的解决方案?

Jon*_*eet 8

相当于:

var last = list.FindLast(predicate);
Run Code Online (Sandbox Code Playgroud)

var last = sequence.Where(predicate).LastOrDefault();
Run Code Online (Sandbox Code Playgroud)

(后者必须检查序列中的所有项目,但是......)

实际上,"Where()"是Find部分,"Last()"分别是"FindLast"的Last部分.同样,FindFirst(predicate)将映射到sequence.Where(predicate).FirstOrDefault()FindAll(predicate)sequence.Where(predicate).


Mar*_*ell 5

LINQ 到对象怎么样:

var item = data.LastOrDefault(x=>x.Whatever == "abc"); // etc
Run Code Online (Sandbox Code Playgroud)

如果您只有 C# 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;
    }
}
Run Code Online (Sandbox Code Playgroud)