in

code for eternity !!!

community website for .net freaks ;-)

Technology

LINQ First and FirstOrDefault

We can use the First extension method of LINQ to return the first element in a sequence that satisfies a specified condition. However the First extension method would throw the System.InvalidOperationException when no element in a sequence satisfies a specified condition. In such a scenario, we can use the FirstOrDefault extenion method which would return the default value of a type instead of throwing the System.InvalidOperationException.

Code example (both in C# and VB.NET) with comments below:

C#:

    // Create a new generic list of ints
    List<int> l = new List<int>();

    l.Add(1); // Add 1 to the list
    l.Add(5); // Add 5 to the list
    l.Add(3); // Add 3 to the list

    // Returns 1 as only 1 satisfies the condition
    int value = l.First(i => i == 1);

    // Returns 5 although both 5 and 3 are greater than 1
    // since 5 appears first in the list
    value = l.First(i => i > 1);

    // Returns the default value of int which is 0
    // since no element in the list equals 4
    value = l.FirstOrDefault(i => i == 4);
   
    // Throws System.InvalidOperationException
    // since no element in the list equals 4
    value = l.First(i => i == 4);

VB.NET:

    ' Create a new generic list of ints
    Dim l As New List(Of Integer)

    l.Add(1) ' Add 1 to the list
    l.Add(5) ' Add 5 to the list
    l.Add(3) ' Add 3 to the list

    ' Returns 1 as only 1 satisfies the condition
    Dim value As Integer = l.First(Function(i) i = 1)

    ' Returns 5 although both 5 and 3 are greater than 1
    ' since 5 appears first in the list
    value = l.First(Function(i) i > 1)

    ' Returns the default value of int which is 0
    ' since no element in the list equals 4
    value = l.FirstOrDefault(Function(i) i = 4)

    ' Throws System.InvalidOperationException
    ' since no element in the list equals 4
    value = l.First(Function(i) i = 4)

Cheers,
Raj

~~~ CODING FOR ETERNITY !!! ~~~

Published Apr 25 2008, 06:22 PM by raj
Filed under: ,

I would really appreciate votes / kicks for this blog post if you found it useful ;-)

  kick it on DotNetKicks.com     Receive Email Updates


Comments

 

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

April 25, 2008 10:45 AM
 

Technology said:

We can use the Single extension method of LINQ to return the only element in a sequence that satisfies

May 10, 2008 7:25 AM

Leave a Comment

(required)  
(optional)
(required)  
Add


StopGlobalWarming.org  
Powered by Community Server (Non-Commercial Edition), by Telligent Systems