使用LINQ从列表中删除元素<T>假设我有LINQ查询,例如:var authors = from x in authorsList where x.firstname == "Bob"
select x;鉴于authorsList是类型的List<Author>,如何删除Author来自authorsList中的查询返回的authors?或者,换句话说,我如何删除所有的名字等于Bob从authorsList?注:为问题的目的,这是一个简化的例子。
3 回答
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();
authorsList
RemoveAll
:
authorsList.RemoveAll(x => x.FirstName == "Bob");
var setToRemove = new HashSet<Author>(authors);authorsList.RemoveAll(x => setToRemove.Contains(x));
泛舟湖上清波郎朗
TA贡献1818条经验 获得超3个赞
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();
- 3 回答
- 0 关注
- 2333 浏览
添加回答
举报
0/150
提交
取消