Using LINQ to remove elements from a List

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

    Below is the example to remove the element from the list.

     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
    
    0 讨论(0)
  • 2020-11-22 11:48

    To keep the code fluent (if code optimisation is not crucial) and you would need to do some further operations on the list:

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

    or

    authorsList = authorsList.Where(x => !setToRemove.Contains(x)).<do_some_further_Linq>;
    
    0 讨论(0)
提交回复
热议问题