是否可以在一个Any()
子句中使用多个where()
?
例如,如果我需要获得最喜欢的啤酒,这个查询将完成这项工作:
var favouriteDrinks = drinks
.Where(f => favouriteBeers
.Any(d => d.drinkID == f.drinkID));
但是,如果我需要获得最喜欢的啤酒和最喜欢的葡萄酒呢?我正在寻找这样的东西:
var favouriteDrinks = drinks
.Where(f => favouriteBeers.Any(d => d.drinkID == f.drinkID) ||
f => favouriteWines.Any(d => drinkID == f.drinkID));
答案 0 :(得分:2)
var favouriteDrinks = drinks
.Where(f => favouriteBeers.Any(d => d.drinkID == f.drinkID) ||
favouriteWines.Any(d => d.drinkID == f.drinkID));
答案 1 :(得分:1)
为什么不这样做:
var favouriteDrinks = drinks.Where(f =>
favouriteBeers.Any(d => d.drinkID == f.drinkID)) ||
favouriteWines.Any(d => d.drinkID == f.drinkID)));
您也可以使用Contains
:
var favouriteDrinks = drinks.Where(f =>
favouriteBeers.Contains(f.drinkID) ||
favouriteWines.Contains(f.drinkID));
答案 2 :(得分:0)
您可以使用.Union()
和.Join()
var favouriteDrinks = favouriteBeers
.Union(favouriteWines)
.Join(drinks,
x => x.drinkID,
y => y.drinkID,
(x,y) => y
);
只要favouriteBeers
和favouriteWines
属于同一类型,此功能就会有效。
答案 3 :(得分:0)
这解决了Tim.Tang的第二个例子。这里有几种方法,但如果归结为"包含" vs" any",我更喜欢包含,因为我的意图更清楚。
var favouriteDrinks = drinks.Where(d =>
favouriteBeers.Select(b => b.drinkId).Contains(d.drinkID) ||
favouriteWines.Select(w => w.drinkId).Contains(d.drinkID));
同样,在你的"饮料"上实现了正确的IEquatable接口。类,你也可以略微简化
var favouriteDrinks = drinks.Where(d =>
favouriteBeers.Contains(d) || favouriteWines.Contains(d));