In this example you will see that what is difference between Enumerable.First() method and Enumerable.FirstOrDefault() method. Enumerable.First() method return a first record but if there is no record found it will throw exception where as Enumerable.FirstOrDefault() method will not throw exception. It will return null if no record found.
Note: Enumerable.First() returns exception "System.InvalidOperationException: Sequence contains no elements"
Let’s see the example.
int[] Arr = { 1, 2, 3, 4, 5, 6 };
int Val = (from i in Arr
where i == 5
select i).First();
Response.Write("<br>Arr:" + Val.ToString());
Output
Arr: 5
int Val2 = (from i in Arr
where i == 6
select i).FirstOrDefault();
Response.Write("<br>Arr2:" + Val2.ToString());
Output
Arr2: 6
int Val3 = (from i in Arr
where i == 10
select i).FirstOrDefault();
Response.Write("<br>Arr3:" + Val3.ToString());
Output
Arr3: 0
int Val4 = (from i in Arr
where i == 10
select i).First();
Response.Write("<br>Arr4:" + Val4.ToString());
Output
-FirstOrDefault()_11a.png)
Download
First()-FirstOrDefault().zip (903.00 bytes)