我需要能够根据其中一个属性中的值是否存在于其他值列表中来选择数据。现在我有这个:
//Just the definition of the different list objects for clarity
List<RouteDataItem> routeData;
List<RouteCodeItem> routeCodes;
var qrData = from d in routeData
where d.Route == RouteType && q.RouteCode == [HERE IS WHERE I'M STUCK]
select q;
routeData是一个对象的List,RouteCode也是如此,所以基本上我想做这样的事情(伪LINQ / SQL类型代码虽然这是纯LINQ2Objects):
//Just the definition of the different list objects for clarity
List<RouteDataItem> routeData;
List<RouteCodeItem> routeCodes;
var qrData = from d in routeData
where d.Route == RouteType && q.RouteCode in (routeCodes.ValidCode)
select q;
我希望你们了解我的象形文字。有没有一种简单的方法来实现这一目标?
答案 0 :(得分:2)
使用Any: -
where d.Route == RouteType && routeCodes.Any(x => x.ValidCode == d.RouteCode)
或使用方法语法: -
var qrData = routeData.Where(d => d.Route == RouteType &&
routeCodes.Any(r => r.ValidCode == d.RouteCode));
答案 1 :(得分:2)
您可以使用Contains
或Any
:
var qrData = from d in routeData
where d.Route == RouteType
&& routeCodes.Select(x => x.ValidCode).Contains(d.RouteCode)
select q;
或
var qrData = from d in routeData
where d.Route == RouteType
&& routeCodes.Any(x => x.ValidCode == d.RouteCode)
select q;
为了更快的查找性能,您可以创建HashSet<T>
:
var validCodes = new HashSet<whateveritis>(routeCodes.Select(x => x.ValidCode));
var qrData = from d in routeData
where d.Route == RouteType && validCodes.Contains(d.RouteCode)
select q;
答案 2 :(得分:1)
你可以试试这个:
var qrData = from d in routeData
where d.Route == RouteType && routeCodes.Any(x => x.ValidCode == d.RouteCode)
select d;
虽然不是100%确定结果选择应该是什么。