Possible Duplicate:
Linq Distinct() use delegate for equality comparer
I need get unique PostViewModel by ID. How do this with lambda expresion?
public IEnumerable<PostViewModel> DistinctPosts
{
get
{
return Employees
.SelectMany(e => e.PostList.Posts)
.Distinct(new PostViewModelComparer())
.ToList();
}
}
comparer:
class PostViewModelComparer : IEqualityComparer<PostViewModel>
{
#region IEqualityComparer<Contact> Members
public bool Equals(PostViewModel x, PostViewModel y)
{
return x.ID.Equals(y.ID);
}
public int GetHashCode(PostViewModel obj)
{
return obj.ID.GetHashCode();
}
#endregion
}
sorry, this is dublicate from Use a delegate for the equality comparer for LINQ's Distinct()
LINQ Distinct is not that smart when it comes to custom objects. All it does is look at your list and see that it has two different objects (it doesn't care that they have the same values for the member fields). One workaround is to implement the IEquatable interface as shown here.
The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.
C# Linq Distinct() method removes the duplicate elements from a sequence (list) and returns the distinct elements from a single data source. It comes under the Set operators' category in LINQ query operators, and the method works the same way as the DISTINCT directive in Structured Query Language (SQL).
If i understand you correctly, I have had a similar issue.
Based on this post, I have made this extension method
public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source,
Func<T, object> keyExtractor)
{
return source.Distinct(new KeyEqualityComparer<T>(keyExtractor));
}
that automatically generates the necessary IEqualityComparer implementation for a given lambda. In your case, that would enable to use something like:
return Employees
.SelectMany(e => e.PostList.Posts)
.Distinct(postViewModel => postViewModel.ID)
.ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With