Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a single element from LINQuery?

Tags:

c#

linq

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?

like image 385
knuffemuffe Avatar asked Dec 06 '25 20:12

knuffemuffe


1 Answers

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;
like image 124
Gilad Green Avatar answered Dec 08 '25 08:12

Gilad Green