Explain the First() and FirstOrDefault() functions in LINQ with C#.
Explain the First() and FirstOrDefault() functions in LINQ with C#.
Technical Content Writer | Blogger
Hi, this is Amrit Chandran. I'm a professional content writer. I have 3+ years of experience in content writing. I write content like Articles, Blogs, and Views (Opinion based content on political and controversial).
First() vs FirstOrDefault() in LINQ (C#)
Both First() and FirstOrDefault() are used to retrieve the first element from a collection, but they behave differently when no matching element is found.
First()
InvalidOperationException) if no element is found.Example-
find the first even number in the list,
Example (Throws Exception)
FirstOrDefault()
nullfor reference types,0for numeric types) if no element is found.Example-
When to Use What?
Also, Read: LINQ Aggregate functions