嵌套的LINQ查询

时间:2013-12-02 04:26:26

标签: linq nested

我正在尝试执行嵌套的linq查询。

public class Sic
{
    public int Id { get; set; }
    public string Code { get; set; }
}

public class Message
{
    public List<Sic> Sics { get; set; }
    public int Id { get; set; }
}

List<Message> msgList = new List<Message>();


Message m1 = new Message
            {
                Id = 0,
                Sics = new List<Sic>()
                    {
                        new Sic() {Id = 0, Code = "A2A"},
                        new Sic() {Id = 1, Code = "A2B"},
                        new Sic() {Id = 2, Code = "A2C"},
                        new Sic() {Id = 3, Code = "A2D"}
                    }
            };

Message m2 = new Message
        {
            Id = 1,
            Sics = new List<Sic>()
                    {
                        new Sic() {Id = 4, Code = "B2A"},
                        new Sic() {Id = 5, Code = "B2B"},
                        new Sic() {Id = 6, Code = "B2C"},
                        new Sic() {Id = 7, Code = "B2D"}
                    }
        };

msgList.Add(m1);
msgList.Add(m2);

List<string> searchList = new List<string> {"A2A", "A2B"};

我想在msgList中找到消息,其中每个消息的Sics包含searchList,即应使用上面的searchList找到m1。

2 个答案:

答案 0 :(得分:1)

你可以使用类似的东西,

msgList.Where(msg=>msg.Sics.Any(sic=>searchList.Contains(sic.Code)));

或者如果您需要匹配所有搜索字词,

msgList.Where(msg => searchList.All(searchTerm=>msg.Sics.Any(sic=>sic.Code==searchTerm)))

答案 1 :(得分:1)

  
    

如果搜索列表中的所有ID都需要匹配

  
msgList.Where(msg => searchList.Any() && searchList.All(s => msg.Sics.Any(sic => s==sic.Code)))
  
    

如果搜索列表中的任何ID需要匹配

  
msgList.Where(msg=>msg.Sics.Any(sic=>searchList.Contains(sic.Code)));