I would like to call FindLast
on a collection which implements IEnumerable
, but FindLast
is only available for List
. What is the 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)
.
How about with LINQ-to-Objects:
var item = data.LastOrDefault(x=>x.Whatever == "abc"); // etc
If you only have C# 2, you can use a utility method instead:
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;
}
}
you can add you collection to a new List by passing it to List<> constructor.
List<MyClass> myList = new List<MyClass>(MyCol);
myList.FindLast....
Use the extension method Last() which is located in the namespace System.Linq.
Your question is invalid because a collection has no last element. A more specialized collection that does have a complete ordering is a list. A more specialized collection that does not have an ordering is a dictionary.
© 2022 - 2024 — McMap. All rights reserved.