I often find myself writing code like this:
collection.First(s => s is MyType) as MyType;
Is there a more specific Linq method, that returns the first element of a certain type?
like this:
collection.FirstOfType<MyType>();
I also looked in Jon Skeets MoreLinq project, but no luck
Use Enumerable.OfType<T> to filter collection by specified type:
collection.OfType<MyType>().First();
Note - if there is possible that no items of MyType exist in collection, then use FirstOrDefault() to avoid exception.
Internally OfType simply uses is operator to yield all items which are compatible with given type. Something like this (actually OfType returns OfTypeIterator which iterates collection):
public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)
{
foreach (object obj in source)
{
if (!(obj is TResult))
continue;
yield return (TResult)obj;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With