knuffemuffe
knuffemuffe

Reputation: 31

Getting a single element from LINQuery?

So I'm new to using LINQ and it seems really useful but I am having some trouble getting the value from a query.

This is my original code that works but I want to replace with LINQ:

foreach (LocationModel loc in locationList)
{
    if (loc.Name.Equals(location, StringComparison.CurrentCultureIgnoreCase))
    {
        locationId = loc.Id;
        break;
    }
}

This is the LINQ I wrote for doing the same thing:

var matchQuery = from loc in locationList
                 where loc.Name.ToLowerInvariant() == location.ToLowerInvariant()
                 select loc.Id;

Now how do I actially get the int Id from matchQuery?

Upvotes: 3

Views: 318

Answers (1)

Gilad Green
Gilad Green

Reputation: 37299

If you want only the first item then use FirstOrDefault:

 var id = (from loc in locationList
           where loc.Name.ToLowerInvariant() == location.ToLowerInvariant()
           select loc.Id).FirstOrDefault();

Or in method syntax:

var id = locationList.FirstOrDefault(loc => loc.Name.ToLowerInvariant() == location.ToLowerInvariant())?.Id;

Upvotes: 2

Related Questions