Linq返回父对象,其子项与单独列表中的所有项匹配

时间:2016-06-09 13:03:58

标签: c# linq entity-framework-6

我有一个对象,它有一个可变长度的项目列表(代码示例中为incomingList)和一个人员列表,每个人员都有一个项目列表。我想只返回那些包含incomingList中所有项目的人。

所以看一下这个例子,我只想让第一和第三人回来。

人们在数据库中,我想尽可能少地检索数据,所以我想弄清楚linq查询需要做什么来实现这个目标?如果我知道incomingList的长度总是一样的话我可以做“......任何(...)&& ... Any(...)&&”等 - 但长度会有所不同。

void Main()
{
    var incomingList = new IncomingItem();

    var matchItem1 = new MatchItem { ItemType = "objectId", ItemValue = "60" };
    var matchItem2 = new MatchItem { ItemType = "area", ItemValue = "CU" };

    incomingList.MatchList = new List<MatchItem>();
    incomingList.MatchList.Add(matchItem1);
    incomingList.MatchList.Add(matchItem2);

    var people = new List<Person>();

    var person1 = new Person { Id = 1 };
    person1.ListOfItems = new List<Item>();
    person1.ListOfItems.Add(new Item { ItemType = "objectId", ItemValue = "60" });
    person1.ListOfItems.Add(new Item { ItemType = "objectId", ItemValue = "1" });
    person1.ListOfItems.Add(new Item { ItemType = "objectId", ItemValue = "30" });
    person1.ListOfItems.Add(new Item { ItemType = "area", ItemValue = "CO" });
    person1.ListOfItems.Add(new Item { ItemType = "area", ItemValue = "CU" });
    people.Add(person1);

    var person2 = new Person { Id = 2 };
    person2.ListOfItems = new List<Item>();
    person2.ListOfItems.Add(new Item { ItemType = "objectId", ItemValue = "60" });
    people.Add(person2);

    var person3 = new Person { Id = 3 };
    person3.ListOfItems = new List<Item>();
    person3.ListOfItems.Add(new Item { ItemType = "objectId", ItemValue = "60" });
    person3.ListOfItems.Add(new Item { ItemType = "area", ItemValue = "CU" });
    people.Add(person3);

    var person4 = new Person { Id = 4 };
    person4.ListOfItems = new List<Item>();
    person4.ListOfItems.Add(new Item { ItemType = "objectId", ItemValue = "12" });
    people.Add(person4);
}

public class IncomingItem
{   
    public IList<MatchItem> MatchList { get; set; }
}

public class MatchItem
{
    public List<object> SomeMoreInformation { get; set; }

    public string ItemType { get; set; }

    public string ItemValue { get; set; }
}

public class Person
{
    public int Id { get; set; }

    public IList<Item> ListOfItems { get; set; }
}

public class Item
{
    public int Id { get; set; }

    public int PersonId { get; set; }

    public string ItemType { get; set; }

    public string ItemValue { get; set; }
}

1 个答案:

答案 0 :(得分:2)

这将返回incomingList中所有ListOfItems项目的所有人:

var result = people.Where(p => incomingList.MatchList
                       .All(l => p.ListOfItems.Select(loi => new { loi.ItemType, loi.ItemValue })
                           .Contains(new { l.ItemType, l.ItemValue }) ));

匿名类型应具有相同名称和类型的属性以解析为“相等”,在这种情况下满足哪种条件。