Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two List<object> into one List in Linq

Tags:

c#

list

linq

I have two lists. BeamElevations<Elevation> and FloorElevations<Elevation>. How can I merge these into Elevations<Elevation> list and order them based on their Elevation using Linq?

like image 904
Vahid Avatar asked Apr 11 '14 15:04

Vahid


People also ask

What is Union C#?

The Union method gets the unique elements from both the lists. Let us set two lists − var list1 = new List<int>{12, 65, 88, 45}; var list2 = new List<int>{40, 34, 65}; Now get the union of both the lists − var res = list1.Union(list2); The following is the example −


1 Answers

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.

like image 123
Selman Genç Avatar answered Sep 20 '22 05:09

Selman Genç