Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq: Method that returns first instance with given type

Tags:

c#

linq

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

like image 437
thumbmunkeys Avatar asked Dec 15 '22 00:12

thumbmunkeys


1 Answers

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;
    }
}
like image 163
Sergey Berezovskiy Avatar answered Jan 06 '23 11:01

Sergey Berezovskiy