.NET[C#]使用LINQ从List<T>集合中删除指定集合元素?
问题描述
实体类(Author):
public class Author{
public int id{get;set;}
public string firstname{get;set;}
public string lastname {get;set;}
}
比如有如下的LINQ查询语句:
var authors = from x in authorsList
select x;
其中,需要从查询集合中删除 firstname=’Bob’ 的所有用户,应该如何实现呢?
方案一
authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();
或者
authorsList.RemoveAll(x => x.firstname == "Bob");
方案二
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();
版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。
发表评论
登录用户才能发表评论, 请 登 录 或者 注册