Using LINQ to remove elements from a List

前端 未结 14 2124
抹茶落季
抹茶落季 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:29

    If you really need to remove items then what about Except()?
    You can remove based on a new list, or remove on-the-fly by nesting the Linq.

    var authorsList = new List()
    {
        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();
    

提交回复
热议问题