Using LINQ to remove elements from a List

前端 未结 14 1992
抹茶落季
抹茶落季 2020-11-22 11:09

Say that I have LINQ query such as:

var authors = from x in authorsList
              where x.firstname == \"Bob\"
              select x;

14条回答
  •  心在旅途
    2020-11-22 11:23

    You cannot do this with standard LINQ operators because LINQ provides query, not update support.

    But you can generate a new list and replace the old one.

    var authorsList = GetAuthorList();
    
    authorsList = authorsList.Where(a => a.FirstName != "Bob").ToList();
    

    Or you could remove all items in authors in a second pass.

    var authorsList = GetAuthorList();
    
    var authors = authorsList.Where(a => a.FirstName == "Bob").ToList();
    
    foreach (var author in authors)
    {
        authorList.Remove(author);
    }
    

提交回复
热议问题