2013-02-18 19 views
0

「每個人」都知道從MoreLinq有用的DistintBy擴展名,我需要用它來清除一個以上的屬性(沒有問題)的列表os對象,當這其中之一屬性是一個列表,這裏是我的自定義類:DistinctBy當不同的屬性是一個列表

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

請注意,只有第一項是不同的,因此,如果我使用下面的代碼,我可以DistinctBy這些項目和結果列表將有2它埃姆斯,並確定。

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

如果我註釋行(//m.EmailAddresses)它不工作,並返回我5項。我怎麼能做到這一點獨特?

+1

爲什麼在比較全班時使用'DistinctBy'? – Rawling 2013-02-18 13:46:54

+0

你想通過評論EmailAddresses來實現什麼? – 2013-02-18 13:49:52

+1

您可以使用帶'IEqualityComparer'的'Distinct'重載,或者使用'string.Join'在匿名類中創建一串電子郵件。 – juharr 2013-02-18 13:52:20

回答

0

DistinctBy對您指定的每個「鍵」都使用默認的相等比較器。 List<T>的默認相等比較器只是比較列表本身的引用。它不檢查兩個列表的內容是否相同。

在你的情況下DistinctBy是錯誤的選擇。您需要使用Enumerable.Distinct並提供在電子郵件地址上使用SequenceEquals的自定義IEqualityComparer

+0

好點,在這個時候我嘗試@juharr所採用的方法,並使用string.Join,稍後我會嘗試實現更'優雅'的IEqualityComparer :) – Ewerton 2013-02-18 14:03:44

相關問題