Search code examples
c#linqentities

How do I get the first value from this collection using Linq to Entities?


I have the following code. The foreach at the end is unnecessary because there will only be one row returned.

So how do I grab a value from userGroups without having to loop?

Thanks Kevin

using (kdEntities db = new kdEntities())
        {
            Label lbl = sender as Label;
            IQueryable<UserGroup> userGroups = from UserGroup in db.UserGroups where UserGroup.UgpID == 1 select UserGroup;

            foreach (var group in userGroups)
            {
                lbl.Text = group.UgpDescription;
            }
        }

Solution

  • userGroups.FirstOrDefault();  
    

    should do the trick