6

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

Community
  • 1
  • 1
Mediator
  • 14,951
  • 35
  • 113
  • 191
  • It would be great if you showed us what your classes look like and how they relate to one another. From what I understand an employee contains a post list which contains individual PostViewModels? – Levi Botelho Dec 20 '12 at 07:25

1 Answers1

2

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(); 
SWeko
  • 30,434
  • 10
  • 71
  • 106