aspx Tutorial

.NET Articles,jQuery demo, asp.net with jQuery, online tutorial,Jquery, SilverLight, Javascript, asp.net,JSON, MVC,.NET Articles,demo, Web Services, .NET articles, Sharepoint 2010, visual studio 2010,Aamir Hasan,IT, Building Your First Web Application Project
Advertise Here

Toolbar

Get our toolbar!

Advertize



Posted by Aamir Hasan   on Wednesday, January 18, 2012 Total Views:  

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

Download

First()-FirstOrDefault().zip (903.00 bytes)

Category: All | ASP.NET 4.O | Linq
Protected by Copyscape Online Plagiarism Tool

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Advertizement 1
Advertizement 2
Advertizement 3
Advertizement 4
Advertizement 5