How to use lambda expression in Distinct

Possible duplicate:
Linq Distinct () use delegate to compare equalities

I need to get a unique PostViewModel by ID. How to 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 the delegate to compare equalities for LINQ's Distinct ()

+6
source share
1 answer

If I understand you correctly, I had a similar problem.

Based on this post , I 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)); } 

which automatically generates the necessary implementation of IEqualityComparer for this lambda. In your case, this will allow you to use something like:

 return Employees .SelectMany(e => e.PostList.Posts) .Distinct(postViewModel => postViewModel.ID) .ToList(); 
+2
source

All Articles