"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 回答
DistinctBy
为您指定的每个"key"使用默认的相等比较器 .List<T>
的默认相等比较器只是比较列表本身的引用 . 它不检查两个列表的内容是否相同 .在你的情况下
DistinctBy
是错误的选择 . 您需要使用Enumerable.Distinct
并提供在电子邮件地址上使用SequenceEquals的自定义IEqualityComparer
.