假设我有 LINQ 查询,例如:
var authors = from x in authorsList
where x.firstname == "Bob"
select x;
鉴于authorsList
类型为List<Author>
,如何从查询返回到authors
authorsList
Author
元素?
或者,换一种说法,我如何从authorsList
删除所有等价的 Bob?
注意:这是出于问题目的的简化示例。
好吧,首先将它们排除会更容易:
authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();
但是,这只会更改authorsList
的值,而不是从先前的集合中删除作者。另外,您可以使用RemoveAll
:
authorsList.RemoveAll(x => x.FirstName == "Bob");
如果您确实需要根据其他集合进行此操作,则可以使用 HashSet,RemoveAll 和 Contains:
var setToRemove = new HashSet<Author>(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));
最好使用List
authorsList.RemoveAll((x) => x.firstname == "Bob");
如果您确实需要删除项目,那么 Except()呢?
您可以基于新列表删除,也可以通过嵌套 Linq 即时删除。
var authorsList = new List<Author>()
{
new Author{ Firstname = "Bob", Lastname = "Smith" },
new Author{ Firstname = "Fred", Lastname = "Jones" },
new Author{ Firstname = "Brian", Lastname = "Brains" },
new Author{ Firstname = "Billy", Lastname = "TheKid" }
};
var authors = authorsList.Where(a => a.Firstname == "Bob");
authorsList = authorsList.Except(authors).ToList();
authorsList = authorsList.Except(authorsList.Where(a=>a.Firstname=="Billy")).ToList();