I have two lists. BeamElevations
and FloorElevations
. How can I merge these into Elevations
List<Elevation> Elevations= FloorElevations.Concat(BeamElevations).ToList();
Use List.AddRange
list1.AddRange(list2);
list1.OrderBy(l => l.Elevation);
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.
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();
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()