假设我有这样的LINQ查询:
var authors = from x in authorsList
where x.firstname == "Bob"
select x;
假设authorsList的类型是List<Author>,我如何从authorsList中删除查询返回的Author元素?
或者,换句话说,我如何从authorsList中删除所有与Bob相同的firstname ?
注意:这是一个简化的例子,以方便提问。
如果你真的需要删除项目,那么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();
下面是从列表中删除元素的示例。
List<int> items = new List<int>() { 2, 2, 3, 4, 2, 7, 3,3,3};
var result = items.Remove(2);//Remove the first ocurence of matched elements and returns boolean value
var result1 = items.RemoveAll(lst => lst == 3);// Remove all the matched elements and returns count of removed element
items.RemoveAt(3);//Removes the elements at the specified index
如果你真的需要删除项目,那么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();