Using LINQ to remove elements from a List

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

    Well, it would be easier to exclude them in the first place:

    authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();
    

    However, that would just change the value of authorsList instead of removing the authors from the previous collection. Alternatively, you can use RemoveAll:

    authorsList.RemoveAll(x => x.FirstName == "Bob");
    

    If you really need to do it based on another collection, I'd use a HashSet, RemoveAll and Contains:

    var setToRemove = new HashSet(authors);
    authorsList.RemoveAll(x => setToRemove.Contains(x));
    

提交回复
热议问题