LINQ query with Distinct and Union

前端 未结 4 1553
[愿得一人]
[愿得一人] 2021-01-01 17:29

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

var q1 = ....
         select new MyModel()
         {
             TheData1 = ...
         


        
4条回答
  •  天涯浪人
    2021-01-01 18:01

    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);
    

提交回复
热议问题