所以我是使用LINQ的新手,它似乎非常有用,但是从查询中获取值时遇到了一些麻烦。
这是我的原始代码,但我想用LINQ替换:
foreach (LocationModel loc in locationList)
{
if (loc.Name.Equals(location, StringComparison.CurrentCultureIgnoreCase))
{
locationId = loc.Id;
break;
}
}
这是我为同样的事情写的LINQ:
var matchQuery = from loc in locationList
where loc.Name.ToLowerInvariant() == location.ToLowerInvariant()
select loc.Id;
现在我如何从matchQuery中获取int Id?
答案 0 :(得分:2)
如果您只想要第一个项目,请使用FirstOrDefault
:
var id = (from loc in locationList
where loc.Name.ToLowerInvariant() == location.ToLowerInvariant()
select loc.Id).FirstOrDefault();
或者在方法语法中:
var id = locationList.FirstOrDefault(loc => loc.Name.ToLowerInvariant() == location.ToLowerInvariant())?.Id;