Linq: method returning the first instance with the given type

I often find that I am writing code as follows:

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 the Jon Skeets MoreLinq project , but no luck

+4
source share
1 answer

Use Enumerable.OfType<T>to filter collections by the specified type:

collection.OfType<MyType>().First();

Note. If it is possible that there are no items in the collection MyType, use FirstOrDefault()to avoid an exception.

OfType is , . - ( OfType OfTypeIterator, ):

public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source)
{
    foreach (object obj in source)
    {
        if (!(obj is TResult))
            continue;

        yield return (TResult)obj;
    }
}
+12

Source: https://habr.com/ru/post/1531633/


All Articles