Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How use lambda expression in Distinct [duplicate]

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

like image 682
Mediator Avatar asked Dec 20 '12 07:12

Mediator


People also ask

Why distinct is not working in Linq?

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.

Can a Lambda statement have more than one statement?

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.

How does Linq distinct work?

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


1 Answers

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(); 
like image 79
SWeko Avatar answered Oct 22 '22 02:10

SWeko