public TElement Last(Func <TElement, bool> predicate) { CachingComparer <TElement> comparer = GetComparer(); using (IEnumerator <TElement> e = source.GetEnumerator()) { TElement value; do { if (!e.MoveNext()) { throw Error.NoMatch(); } value = e.Current; } while (!predicate(value)); comparer.SetElement(value); while (e.MoveNext()) { TElement x = e.Current; if (predicate(x) && comparer.Compare(x, false) >= 0) { value = x; } } return(value); } }
public static TSource First <TSource>(this IEnumerable <TSource> source, Func <TSource, bool> predicate) { if (source == null) { throw Error.ArgumentNull("source"); } if (predicate == null) { throw Error.ArgumentNull("predicate"); } OrderedEnumerable <TSource> ordered = source as OrderedEnumerable <TSource>; if (ordered != null) { return(ordered.First(predicate)); } foreach (TSource element in source) { if (predicate(element)) { return(element); } } throw Error.NoMatch(); }
public static TSource Single <TSource>(this IEnumerable <TSource> source, Func <TSource, bool> predicate) { if (source == null) { throw Error.ArgumentNull(nameof(source)); } if (predicate == null) { throw Error.ArgumentNull(nameof(predicate)); } using (IEnumerator <TSource> e = source.GetEnumerator()) { while (e.MoveNext()) { TSource result = e.Current; if (predicate(result)) { while (e.MoveNext()) { if (predicate(e.Current)) { throw Error.MoreThanOneMatch(); } } return(result); } } } throw Error.NoMatch(); }
public static TSource Last <TSource>(this IEnumerable <TSource> source, Func <TSource, bool> predicate) { if (source == null) { throw Error.ArgumentNull(nameof(source)); } if (predicate == null) { throw Error.ArgumentNull(nameof(predicate)); } OrderedEnumerable <TSource> ordered = source as OrderedEnumerable <TSource>; if (ordered != null) { return(ordered.Last(predicate)); } IList <TSource> list = source as IList <TSource>; if (list != null) { for (int i = list.Count - 1; i >= 0; --i) { TSource result = list[i]; if (predicate(result)) { return(result); } } } else { using (IEnumerator <TSource> e = source.GetEnumerator()) { while (e.MoveNext()) { TSource result = e.Current; if (predicate(result)) { while (e.MoveNext()) { TSource element = e.Current; if (predicate(element)) { result = element; } } return(result); } } } } throw Error.NoMatch(); }
public static TSource First <TSource>(this IEnumerable <TSource> source, Func <TSource, bool> predicate) { TSource first = source.TryGetFirst(predicate, out bool found); if (!found) { throw Error.NoMatch(); } return(first); }
public static TSource Last <TSource>(this IEnumerable <TSource> source, Func <TSource, bool> predicate) { bool found; TSource last = source.TryGetLast(predicate, out found); if (!found) { throw Error.NoMatch(); } return(last); }