Merge two List<object> into one List in Linq

前端 未结 5 634
猫巷女王i
猫巷女王i 2020-12-05 15:12

I have two lists. BeamElevations and FloorElevations. How can I merge these into Elevations

相关标签:
5条回答
  • 2020-12-05 15:43
     List<Elevation> Elevations= FloorElevations.Concat(BeamElevations).ToList();
    
    0 讨论(0)
  • 2020-12-05 15:49

    Use List.AddRange

       list1.AddRange(list2);
       list1.OrderBy(l => l.Elevation);
    
    0 讨论(0)
  • 2020-12-05 15:55

    Use Concat and OrderBy

    var result = list1.Concat(list2).OrderBy(x => x.Elevation).ToList();
    

    If you want to remove duplicates and get an unique set of elements you can also use Union method:

    var result = list1.Union(list2).OrderBy(x => x.Elevation).ToList();
    

    In order to make it work properly you need to overide Equals and GetHashCode methods in your class.

    0 讨论(0)
  • 2020-12-05 15:55

    Initially you merge them like below:

    Elevations=BeamElevations.Union(FloorElevations)
                             .ToList();
    

    Then

    Elevations=Elevations.OrderBy(x=>x.Elevation)
                         .ToList();
    

    Or in one step:

    Elevations=BeamElevations.Union(FloorElevations)
                             .OrderBy(x=>x.Elevation)
                             .ToList();
    

    Another way to achieve this would be to use Concat

    Elevations=BeamElevations.Concat(FloorElevations)
                             .OrderBy(x=>x.Elevation)
                             .ToList();
    
    0 讨论(0)
  • 2020-12-05 16:01

    If there are any devs out there that might be looking for a solution in VB.NET, here you go:

    Dim list1 As List(Of MyObject)
    Dim list2 As List(Of MyObject)
    Dim mergedAndSortedList As List(Of MyObject)
    
    mergedAndSortedList = (From obj In list1.Union(list2)
                           Order By obj.MyPropertyToSortOn
                           Select obj).ToList()
    
    0 讨论(0)
提交回复
热议问题