score:2

Accepted answer

IEnumerable<Element>.Cast<SomeClass>().FirstOrDefault(); is probably want you want, but the answer has nothing to do with performance.

Unless Element is IEnumerable, it doesn't make sense to use Cast() on the result of FirstOrDefault(), and will result in a compile error.

Assuming you meant (SomeClass)(IEnumerable<Element>.FirstOrDefault()); for your second case, this is also problematic because if IEnumerable<Element> is empty, then FirstOrDefault() will return null if Element is a reference type, or default construct Element if it's a value type. It would be preferable to default construct SomeClass in the event that IEnumerable<Element> is empty and SomeClass is a value type, rather than attempting to cast from Element to SomeClass.

IEnumerable<Element>.Cast<SomeClass>().FirstOrDefault(); will only ever perform a maximum of one cast from Element to SomeClass because LINQ chains are lazily enumerated.


Related Articles