Linq to 实体从列表中删除
Linq to entities remove from list
当列表 (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));
给定一个人员列表,例如:
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
class 来完成示例!
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
并展示它的工作原理:
当列表 (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));
给定一个人员列表,例如:
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
class 来完成示例!
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
并展示它的工作原理: