LINQ First()

When querying for a single item, bringing back a collection from a query brings back an enumerable list when all you wanted was a single item.  You can use the First() method to return the first item in the list, thus getting the item from the query as such:

var data = (from o in Orders
               where o.OrderID = id
               select o.Name).First();

However, it may cause problems if no records exist in the query, so it may be more beneficial to do:

var data = (from o in Orders
               where o.OrderID = id
               select o.Name);

if (data.Count() == 0)
    return string.Empty;
else
    return data.First();

Published Thursday, January 10, 2008 5:07 AM by bmains
Filed under:

Comments

# Link Listing - January 9, 2008

Wednesday, January 09, 2008 11:45 PM by Christopher Steen

Link Listing - January 9, 2008

# Link Listing - January 9, 2008

Wednesday, January 09, 2008 11:45 PM by Christopher Steen

MSBuild Porting an NAnt Task to MSBuild [Via: Scott Dorman ] WPF Lawson Client - Great looking WPF...

# re: LINQ First()

Thursday, January 10, 2008 7:38 AM by Horst

Have you tried FirstOrDefault() ?

# re: LINQ First()

Friday, January 11, 2008 3:58 PM by kazimanzurrashid

To avoid the exception when no record exists use FirstOrDefault.

The leading UI suite for ASP.NET - Telerik radControls
Outstanding performance. Full ASP.NET AJAX support. Nearly codeless development.