将循环转换为linq表达式

时间:2015-05-16 13:48:29

标签: c#

我有两个清单。请参阅下面的代码:

public class Person
{
    public string Name { get; set; }
    public int ItemOneId { get; set; }
    public int ItemTwoId { get; set; }
}

public class Item
{
    public int ItemOneId { get; set; }
    public int ItemTwoId { get; set; }
}

List<Person> persons = new List<Person>
{
    new Person
    {
        Name = "a",
        ItemOneId = 11,
        ItemTwoId = 23
    },
    new Person
    {
        Name = "c",
        ItemOneId = 11,
        ItemTwoId = 56
    },
    new Person
    {
        Name = "d",
        ItemOneId = 109,
        ItemTwoId = 59
    }
};

List<Item> items = new List<Item>
{
    new Item
    {
        ItemOneId = 11,
        ItemTwoId = 56
    },
    new Item
    {
        ItemOneId = 1,
        ItemTwoId = 2
    }
};

我想从人员列表中获取所有人员,其中ItemOneId和ItemTwoId不存在于项目列表中。我有以下代码 - 是更好的解决方案吗?

List<Person> result = new List<Person>();
foreach(Person person in persons)
{
    if (!items.Any(x => x.ItemOneId == person.ItemOneId && x.ItemTwoId == person.ItemTwoId))
    {
        result.Add(person);
    }
}

或者可能没有其他解决方案?

1 个答案:

答案 0 :(得分:2)

以下代码应该有效!

var result = persons.Where(p => !items.Any(x => x.ItemOneId == p.ItemOneId && x.ItemTwoId == p.ItemTwoId);