2017-08-30 130 views
-2

刪除重複IEnumerable 如何從給定的集合集合中刪除重複的內容?不考慮訂單。 從IEnumerable <IEnumerable <T>>

例如。

IEnumerable<IEnumerable<T>> Collection = [{1,2,3} , {2,1,3}, {1,1,2}, {1,2,2}] 

應該

IEnumerable<IEnumerable<T>> Collection = [{1,2,3} , {1,1,2}, {1,2,2}] // [ {2,1,3}, {1,1,2}, {1,2,2}] is also valid 

**編輯**

我明白,對於IEnumerables E1和E2我可以做這樣的事情,找到重複:

bool equal = (E1.Count() == E2.Count() && (!E1.Except(E2).Any() || !E2.Except(E1).Any())) 

if(equal) 
{ 
    //Do something 
} 

但是,如何做類似

IEnumerable<IEnumerable<T>> 
+0

你有試過什麼嗎?你有什麼想法解決這個問題?這不是一個代碼寫入服務。所以,你希望你在來之前展現出一些努力並提出具體的問題。 –

+0

請提供一些編譯和顯示您以前的工作的代碼。 – Sefe

+0

你可以找到這個線程相當有用:https://softwareengineering.stackexchange.com/questions/339317/find-duplicate-in-a-list-of-a-list-of-integers/339318#339318 – Absurd

回答

1

訣竅是建立一個新的列表,只包含唯一的項目。您的支票確實沒有 不適用於所有邊緣情況(例如,您的支票是成功的{1, 1, 2} == {1, 2, 3},因爲只能比較值類型的平等性而非身份)。

最簡單的方法就是分類收集和比使用Enumerable.SequenceEqual

public static class Helper 
{ 
    public static IEnumerable<IEnumerable<int>> Unique(this IEnumerable<IEnumerable<int>> source) 
    { 
     var list = new List<List<int>>(); // sorted reference list. 

     foreach (var toCompare in source) 
     { 
     var toComp = toCompare.OrderBy(x => x).ToList(); // prevent multiple enumerations. 
     if (!list.Any(item => toComp.SequenceEqual(item))) 
     { 
      list.Add(toComp); 
      yield return toCompare; // return the unsorted one! 
     } 
     } 
    } 
} 

的使用

var unique = collection.Unique(); 

怎麼以上工作代碼:

我們把所有的參考名單返回的項目,但參考列表已排序。然後,我們枚舉源列表,對每個項目進行排序,並檢查它是否已經在我們的參考列表中,如果不是,我們將排序的項目添加到參考列表中,並將未排序的原始項目添加到yield return

相關問題