2012-12-20 9 views
6

thể trùng lặp:
Linq Distinct() use delegate for equality comparerLàm thế nào sử dụng biểu thức lambda trong biệt

tôi cần có được PostViewModel độc đáo bởi ID. Làm thế nào để điều này với 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 
} 

xin lỗi, đây là dublicate từ Use a delegate for the equality comparer for LINQ's Distinct()

+0

Thật tuyệt vời nếu bạn cho chúng tôi biết lớp học của bạn trông như thế nào và chúng có liên quan như thế nào với nhau. Từ những gì tôi hiểu một nhân viên có chứa một danh sách bài viết có chứa PostViewModels cá nhân? –

Trả lời

2

Nếu tôi hiểu bạn một cách chính xác, tôi đã có một vấn đề tương tự.

Dựa trên this post, tôi đã thực hiện phương pháp mở rộng này

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

tự động tạo ra việc thực hiện IEqualityComparer cần thiết cho một lambda nhất định. Trong trường hợp của bạn, điều đó sẽ cho phép sử dụng một cái gì đó như:

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