Alex Rivera | Logout

LINQ query with Distinct and Union

Asked 2011-03-11T17:23:13.180
24

I currently have 2 queries that are returning lists of MyModel like this:

var q1 = ....
         select new MyModel()
         {
             TheData1 = ...
             TheData2 = ...
             TheUniqueID = ...
         }

var q2 = ....
         select new MyModel()
         {
             TheData1 = ...
             TheData2 = ...
             TheUniqueID = ...
         }

If in q1 I have:

TheUniqueID = 2,3,6,9,11 

and in q2 I have:

TheUniqueID = 2,4,7,9,12

How do write the query so that I get a list of MyModel where

TheUniqueID = 2,3,4,6,7,9,11,12

In other words, each TheUniqueID is present only once (ie. 2 and 9 not repeated).

I started looking at Union and distinct but I'm wondering if I need 2 from statements or not.

Any suggestions are welcome.

Edit
Report

2 Answers

14

Union creates an Enumerable with unique values from both collections. In other words, you don't need Distinct.

edit: example of Union here

edit2: forgot that it's not the list of UniqueIDs that you're concatenating. I removed the suggested code since it was wrong. You should be able to do a simple Union if you implement an IEqualityComparer, but that might be overkill.

answered 2011-03-11T17:31:42.110
6

As was pointed out if you are combining the lists with .Union() you will have to define uniqueness by using the overload passing an IEqualityComparer for your type.

var result = q1.Union(q2, myEqualityComparer);

otherwise, and easier you could use DistinctBy( x=> x.TheUniqueId) from the MoreLinq project:

var result = q1.Concat(q2).DistinctBy(c => c.TheUniqueID);
answered 2011-03-11T17:29:21.550

Your Answer