C# DistinctBy当distinct的属性为列表时

C# DistinctBy当distinct的属性为列表时,c#,linq,distinct,C#,Linq,Distinct,“Everyone”知道有用的DistintBy扩展,我需要使用它通过多个属性(没有问题)来区分list os对象,当其中一个属性是list时,我的自定义类如下: public class WrappedNotification { public int ResponsibleAreaSourceId { get; set; } public int ResponsibleAreaDestinationId { get; set; } public List<Str

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

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

如果我对行(//m.EmailAddresses)进行注释,它将不起作用,并返回5项。如何进行区分?

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


在您的情况下,
DistinctBy
是错误的选择。您需要使用
可枚举.Distinct
,并提供一个自定义的
IEqualityComparer
,用于电子邮件地址。

当您比较整个类时,为什么要使用
DistinctBy
呢?您想通过注释
电子邮件地址来实现什么?您可以使用
Distinct
的重载获取
IEqualityComparer
,或使用
string.Join
在匿名类中创建电子邮件字符串。@Rawling:很可能不是这样。将DistinctBy与类声明进行比较。它包含类中未声明的
EvalStatus
。由此我推断OP缩短了类声明,实际上它有更多的属性。很好,现在我尝试@juharr建议的方法并使用字符串。Join,稍后我将尝试实现更“优雅”的IEqualityComparer:)
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"));
 notifications = notifications.DistinctBy(m => new
 {
     m.ResponsibleAreaSourceId,
     m.ResponsibleAreaDestinationId,
     //m.EmailAddresses,
     m.EvalStatus
 }).ToList();