Hi
Onetime i was giving interview then i got this question.Then i told both is used for same purpose. But it was not the exact answer.
In simple word, FirstOrDefault() will handle the exception but First() will not handle the exception.
First() and FirstOrDefault() are two extension methods of the Enumerable class.
So lets test with some example in asp.net
protected void Page_Load(object sender, EventArgs e) { int[] number = { 1, 5, 6 }; var num = number.Where(n => n > 10).FirstOrDefault();; Response.Write(num); }
Note: This code will not throws the exception. So if we have to handle the exception then we can use FirstOrDefault();.
Now lets test with First()
protected void Page_Load(object sender, EventArgs e) { int[] number = { 1, 5, 6 }; var num = number.Where(n => n > 10).First(); Response.Write(num); }
Note: This code will throw the exception.
Your blog is nice Chandra!
You are noting down each stuff you learn.. & they are helpful for others.. Great Job!
Thank you sir. I m really happy to see your nice comment on my blog.