如何在Distinct中使用lambda表达式

时间:2012-12-20 07:22:21

标签: c# linq lambda distinct

  

可能重复:
  Linq Distinct() use delegate for equality comparer

我需要通过ID获取唯一的PostViewModel。如何使用lambda expresion?

public IEnumerable<PostViewModel> DistinctPosts
{
  get 
  { 
    return Employees
             .SelectMany(e => e.PostList.Posts)
             .Distinct(new PostViewModelComparer())
             .ToList(); 
  }
}

比较器:

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
}
抱歉,这是来自Use a delegate for the equality comparer for LINQ's Distinct()

的公告

1 个答案:

答案 0 :(得分:2)

如果我理解正确,我也有类似的问题。

基于this post,我制作了此扩展方法

public static IEnumerable<T> Distinct<T>(this IEnumerable<T> source, 
                                         Func<T, object> keyExtractor)
{
  return source.Distinct(new KeyEqualityComparer<T>(keyExtractor));
}

自动为给定的lambda生成必要的IEqualityComparer实现。在您的情况下,这将使用以下内容:

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