Getting a single element from LINQuery?
So, I'm new to using LINQ and it seems really useful, but I'm having trouble getting a value from a query.
This is my original code that works, but I want to replace LINQ:
foreach (LocationModel loc in locationList)
{
if (loc.Name.Equals(location, StringComparison.CurrentCultureIgnoreCase))
{
locationId = loc.Id;
break;
}
}
This LINQ I wrote to do the same:
var matchQuery = from loc in locationList
where loc.Name.ToLowerInvariant() == location.ToLowerInvariant()
select loc.Id;
Now, how can I get the int id from matchQuery?
+3
source to share
1 answer
If you only want the first element then use FirstOrDefault
:
var id = (from loc in locationList
where loc.Name.ToLowerInvariant() == location.ToLowerInvariant()
select loc.Id).FirstOrDefault();
Or in the syntax of the method:
var id = locationList.FirstOrDefault(loc => loc.Name.ToLowerInvariant() == location.ToLowerInvariant())?.Id;
+2
source to share