区别时,不同的属性是列表

时间:2013-02-18 13:43:49

标签: c# linq distinct

“Everyone”知道来自MoreLinq的有用的DistintBy扩展,我需要使用它来通过多个属性区分列表os对象(没有问题),并且当其中一个属性是列表时,这是我的自定义类:

public class WrappedNotification
{
    public int ResponsibleAreaSourceId { get; set; }
    public int ResponsibleAreaDestinationId { get; set; }
    public List<String> EmailAddresses { get; set; }
    public string GroupName { get; set; }
}

在测试文件中创建一些对象并尝试区分这些项目

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"));

请注意,只有第一项是不同的,所以如果我使用以下代码我可以区分这些项目,结果列表将有2项,并且确定。

 notifications = notifications.DistinctBy(m => new
 {
     m.ResponsibleAreaSourceId,
     m.ResponsibleAreaDestinationId,
     //m.EmailAddresses,
     m.EvalStatus
 }).ToList();

如果我评论该行(//m.EmailAddresses)它不起作用并返回5个项目。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

DistinctBy对您指定的每个“键”使用默认的相等比较器。 List<T>的默认相等比较器只是比较列表本身的引用。它不检查两个列表的内容是否相同。

在您的情况下DistinctBy是错误的选择。您需要使用Enumerable.Distinct并提供在电子邮件地址上使用SequenceEquals的自定义IEqualityComparer