linq query form

前端 未结 3 1614
自闭症患者
自闭症患者 2021-01-14 22:50

How can be the following code converted to linq or predicate expression:

List list1 = new List {1,2,3,4,5};
List list2= new          


        
相关标签:
3条回答
  • 2021-01-14 23:28

    You could do something like this:

    list1.ForEach( x => { list2.Remove(x); } );
    
    0 讨论(0)
  • 2021-01-14 23:32

    You can use Except():

    list2 = list2.Except(list1)
                 .ToList();
    

    This also will perform better than your original code, since your code is O(n2) doing a loop over all items in the first collection, then trying to find the first match in the second collection. (Although admittedly the performance difference will not matter much if your collections are this small, but it will matter significantly for large collections).

    Except() will create a HashSet<int> of list1 internally and then just traverse the list2 collection. Only items that are not contained in the HashSet end up in the result enumeration - since the HashSet lookup is O(1) on average this will result in O(n) effort all in all.

    For an educational refresher see Jon Skeets EduLinq series, here the chapter for Except.

    0 讨论(0)
  • 2021-01-14 23:39
    list2.RemoveAll(m=>list1.Contains(m));
    
    0 讨论(0)
提交回复
热议问题