C# Linq - 如何从仅包含另一个列表项目的列表中选择项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17297906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:05:04  来源:igfitidea点击:

Linq - How to select items from a list that contains only items of another list?

c#linqentity-framework

提问by Gypsy

I have this two classes:

我有这两个类:

public class Item
{
   public int Id{get;set;}
   public List<Test> TestList{get;set;} 
}
public class Test
{ 
   public int Id{get;set;}
   public Item Item{get;set;}
   public byte State{get;set;}
}

Item Class Data:

项目类别数据:

Id
 1
 2
 3

And Test Class Data:

和测试类数据:

Item   State
  1      1
  1      2
  1      3
  2      1
  2      4
  3      2

Now i need to write a query that select the Items from my class that just have state of 1 and 2.For example for the sample above it should returns row with Item=3. i wrote this query:

现在我需要编写一个查询,从我的类中选择状态为 1 和 2 的项目。例如,对于上面的示例,它应该返回带有 Item=3 的行。我写了这个查询:

var stateList=new List<byte>(){1,2};
Items.Where(x => x.TestList.Select(c => c.State).Any(s => stateList.Contains(s)));

but it returns Item=1 either.Any Idea?

但它也返回 Item=1。有什么想法吗?

采纳答案by Ahmed KRAIEM

This returns the items which all states are in stateList, I think that that's what you need:

这将返回所有状态所在的项目stateList,我认为这就是您所需要的:

Items.Where(x => x.TestList.All(s => stateList.Contains(s.State)));

回答by Yaugen Vlasau

in case you need only those items which TestList have only items with status 2:

如果您只需要 TestList 只有状态为 2 的项目的那些项目:

tems.Where( i => i.TestList.All(li => li.State == 2))