Linq to entities从列表中删除

时间:2015-02-12 14:13:40

标签: c# linq-to-entities removeall

我想从列表(id)中得出结论时从实体列表中删除项目。我已经编写了这段代码,但我猜测有更好的方法可以做到这一点,并提高性能。

这是我的代码:

List<int> toRemove; //includes the ids of the entities to be removed
        if (people.Count > 1)
            people.RemoveAll(x => people.Any(y => y != x && toRemove.Contains(x.ID)));
        else
            people.RemoveAll(x => toRemove.Contains(x.ID));

1 个答案:

答案 0 :(得分:1)

给出一个人员列表,例如:

var people = new List<Person>
{
    new Person { ID = 1, Name = "Fred1" },
    new Person { ID = 2, Name = "Fred2" },
    new Person { ID = 3, Name = "Fred3" },
    new Person { ID = 4, Name = "Fred4" },
    new Person { ID = 5, Name = "Fred5" },
    new Person { ID = 6, Name = "Fred6" },
    new Person { ID = 7, Name = "Fred7" },
    new Person { ID = 8, Name = "Fred8" },
    new Person { ID = 9, Name = "Fred9" },
    new Person { ID = 10, Name = "Fred10" }
};

要删除的ID列表:

List<int> toRemove = new List<int> { 3, 4, 5 };

您可以删除不需要的条目,如下所示:

people = people.Where(p => !toRemove.Contains(p.ID)).ToList();

哦,为了完整起见,这里有一个Person课来完成这个例子!

public class Person
{
    public int ID { get; set; }
    public string Name { get; set; }
}

并表明它有效:

https://ideone.com/ERP3rk