[英]linq query selecting all elements of certain value but none of another value
I have a table that looks somewhat like this: 我有一个看起来像这样的表:
| FruitID | BasketID | FruitType |
I'm passing in the query a list of BasketIDs
and I want the list of FruitIDs
that are within the BasketID
AND that are only of a certain FruitType
(values can only 1 or 2). 我通过查询列表
BasketIDs
和我想的列表FruitIDs
是内BasketID
和只有在一定FruitType
(值只能1或2)。
This is what I have: 这就是我所拥有的:
var TheQuery = (from a in MyDC.MyTable
where TheBasketIDs.Contains(a.BasketID) &&
a.FruitType == 1 // need help here
select a.FruitID).ToList();
I'm having some difficulty expressing the second where
condition. 我有一些难以表达的第二个
where
条件。 I want the FruitIDs
where all the FruitType
are all 1s and none are 2s. 我想要
FruitIDs
,其中所有FruitType
都是1,没有2是2。
| FruitID | BasketID | FruitType |
| 23 | 2 | 1 |
| 23 | 5 | 1 |
| 19 | 2 | 1 |
| 19 | 5 | 2 |
For instance, Fruit 23 is ok because its FruitType
is always 1 but Fruit 19 isn't ok because it also has a FruitType
of 2, even if the list of TheBasketIDs
I'm passing in doesn't contain a 5. 例如,Fruit 23没问题,因为它的
FruitType
总是1,但Fruit 19不好,因为它的FruitType
也是2,即使我传入的TheBasketIDs
列表中不包含5。
One way to do this would be to group by fruit id, and then examine the resultant groups with LINQ expressions: 执行此操作的一种方法是按果ID分组,然后使用LINQ表达式检查结果组:
var ids = MyDC.MyTable
.GroupBy(r => r.FruitID)
// The following condition examines g, the group of rows with identical FruitID:
.Where(g => g.Any(item => TheBasketIDs.Contains(item.BasketID))
&& g.Any(item => item.FruitType == 1)
&& g.All(item => item.FruitType != 2))
.Select(g => g.Key);
This produces the list of FruitID
s of your desired type. 这将生成所需类型的
FruitID
列表。
EDIT: (in response to a comment below) 编辑:(回应下面的评论)
Type is only 1 or 2 but never 3
类型只有1或2但从不3
Then you can simplify your query as follows: 然后,您可以按如下方式简化查询:
var ids = MyDC.MyTable
.GroupBy(r => r.FruitID)
// The following condition examines g, the group of rows with identical FruitID:
.Where(g => g.Any(item => TheBasketIDs.Contains(item.BasketID))
// When there is no 3-rd state, FruitType==1 will keep FruitType==2 out
&& g.All(item => item.FruitType == 1))
.Select(g => g.Key);
var TheQuery = (from a in MyDC.MyTable
group a by a.FruitID into g
where g.Any(b => TheBasketIDs.Contains(b.BasketID)) && g.All(b => b.FruitType == 1)
select g.Key).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.