Wednesday 20 September 2017

How use Distinct in linq & linq to NHibernate by some columns

You can use GroupBy:
var result = myList.GroupBy(a => new { a.Province, a.City })
      .Select(g => new Address { 
                  Province = g.Key.Province, 
                  City = g.Key.City 
              });
Or use anonymous type:
 myList.Select(a => new { 
            Province = a.Province,
            City = a.City
        })
      .Distinct();
By default, anonymous type uses value quality to compare, it is equivalent when all properties are equivalent.
Another way is to customer EqualityComparer which uses Province and City for Equal and GetHashCode method with another overload Distinct in here

No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Blog Archive