Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq union of two lists

Tags:

c#

linq

I have an object model that contains a list of longs. I want to get the combined list of longs of two different instances. When I write this:

var MyCombinedList = TheObject1.ListOfLongs.Union(TheObject2.ListOfLongs);

I get an empty list. Note that sometimes TheObject2 can have an empty list.

What am I doing wrong?

Thanks.

like image 224
frenchie Avatar asked Oct 21 '12 16:10

frenchie


People also ask

Is the Union method gets the unique elements from both the lists?

Union is an extension method to merge two collections. It requires at least two collections to perform the merge operation, but that merged collection holds only the distinct elements from both the collections.

Does Union remove duplicates Linq?

Linq, acts upon 2 collections. It returns a new collection that contains the elements that are found. Union removes duplicates.

Which operator returns distinct elements in two sets?

The following table lists all Set operators available in LINQ. Returns distinct values from a collection. Returns the difference between two sequences, which means the elements of one collection that do not appear in the second collection.


1 Answers

Use Concat() this will concatenates two sequences. So try this instead :

var MyCombinedList = TheObject1.ListOfLongs.Concat(TheObject2.ListOfLongs);

Good Luck !!

like image 90
Kundan Singh Chouhan Avatar answered Sep 30 '22 17:09

Kundan Singh Chouhan