April 10, 2009

Return the First Element of a Sequence in LINQ




If you have a List<string> and want to quickly retrieve the first item of the sequence, use FirstOrDefault()

Enumerable.FirstOrDefault() returns the first element of a sequence, or a default value if the sequence contains no elements. For eg: Running the following query returns 'Jack'

C#


void Main()


{


    List<string> list = new List<string>() { "Jack", "And", "Jill", "Went", "Up", "The", "Hill" };


    var first = list.FirstOrDefault();


    Console.WriteLine(first);


}




VB.NET


Private Sub Main()


    Dim list As New List(Of String)(New String() {"Jack", "And", "Jill", "Went", "Up", "The", "Hill"})


    Dim first = list.FirstOrDefault()


    Console.WriteLine(first)


End Sub




Similarly if FirstOrDefault is used on an empty list of integers, it returns 0

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Return the First Element of a Sequence in LINQ"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions