DistinctBy when the property to distinct is a list
"Everyone" knows the usefull DistintBy extension from MoreLinq, i need to use it to distinct a list os object by more than one property (no problem with it) and when one of this properties is a list, here is my custom class:
public class WrappedNotification
{
public int ResponsibleAreaSourceId { get; set; }
public int ResponsibleAreaDestinationId { get; set; }
public List<String> EmailAddresses { get; set; }
public string GroupName { get; set; }
}
In a test file a create some objects and try to distinct this items
List<WrappedNotification> notifications = new List<WrappedNotification>();
notifications.Add(new WrappedNotification(1, 1, new List<string>() { "email" }, EvaluationStatus.Approved, "group"));
notifications.Add(new WrappedNotification(0, 1, new List<string>() { "email" }, EvaluationStatus.Approved, "group"));
notifications.Add(new WrappedNotification(0, 1, new List<string>() { "email" }, EvaluationStatus.Approved, "group"));
notifications.Add(new WrappedNotification(0, 1, new List<string>() { "email" }, EvaluationStatus.Approved, "group"));
notifications.Add(new WrappedNotification(0, 1, new List<string>() { "email" }, EvaluationStatus.Approved, "group"));
Note that only the first item is different, so if i use the following code i can DistinctBy these items and the result list will have 2 items, and its ok.
notifications = notifications.DistinctBy(m => new
{
m.ResponsibleAreaSourceId,
m.ResponsibleAreaDestinationId,
//m.EmailAddresses,
m.EvalStatus
}).ToList();
If i comment the line (//m.EmailAddresses) it dont work and returns me 5 items. How can i do this Distinct?
DistinctBy
uses the default equality comparer for every "key" you specify. The default equality comparer for List<T>
just compares the references of the list itself. It doesn't check if the contents of the two lists are the same.
In your case DistinctBy
is the wrong choice. You need to use Enumerable.Distinct
and supply a custom IEqualityComparer
that uses SequenceEquals
on the email addresses.
上一篇: 一个短语中的两个单词组。 C#