2017-10-12 121 views
2

我有一個包含2個字段的C#列表。我需要根據Field1找到重複項,但排除那些Field2對於給定的重複項對也相同的重複項。換句話說:在列表中找到重複項並根據其他字段排除項目

Field1 Field2 
------------- 
0  0 
0  1 

應該是結果,而

Field1 Field2 
------------- 
0  1 
0  1 

不應該在結果中。
到目前爲止,我得到這個:

dups = myList 
    .AsParallel() 
    .GroupBy(x => x.field1) 
    .Where(x => x.Count() > 1) 
    .Select(x => x.Key); 

但我不知道如何排除基於Field2

+0

你是什麼意思,在哪裏Field2也是一樣的?你的意思是你想排除'Field2'被複制,但具有相同'Field1'的結果? – GeorgeChond

+0

是的,這正是我想要做的。 – Manngo

+0

當有重複的條目時,是否要保留一個(一行'0 1'而不是兩個)或避免全部(不是兩行爲「0 1」)? – Pac0

回答

0

沒有太多有效的,但做這項工作(如果我理解問題吧):

myList.GroupBy(x=>x.field1) 
     .Where(g=>g.Count()>1) 
     .SelectMany(g=>g) 
     .GroupBy(x=>new{x.field1,x.field2}) 
     .Where(g=>g.Count()==1) 
     .SelectMany(g=>g); 

對於下面的一些元組的樣本:

var myList = new List<Tuple<int,int>>{ 
    new Tuple<int,int>(1,2), 
    new Tuple<int,int>(1,2), 
    new Tuple<int,int>(1,3), 
    new Tuple<int,int>(1,4), 
    new Tuple<int,int>(2,3), 
    new Tuple<int,int>(2,4), 
}; 

這個回報率(跑linqpad) :

enter image description here

+0

您的'where'條款是否會刪除所有重複的條目,而不是保留每條條目(只刪除重複的條目)? (不知道我是否正確理解了OP的請求) – Pac0

+0

我認爲OP需要基於'field1'的所有副本;但是想排除那些在'field2'上也是重複的,(不知道我是否理解正確。) – mshsayem

0

我會去創建一個自定義IEqualityComparer

class MyClass { 
    public int field1; 
    public int field2; 
} 

class MyClassComparer: EqualityComparer<MyClass> 
{ 
    public override bool Equals(MyClass x, MyClass y) 
    { 
     if (x == null && y == null) 
      return true; 
     else if (x == null || x == null) 
      return false; 

     if (x.field1 == y.field1 && x.field2 == y.field2) 
     { 
      return true; 
     } 
     else 
     { 
      return false; 
     } 
    } 

    public override int GetHashCode(MyClass x) 
    { 
     int hCode = x.field1.GetHashCode()^x.field2.GetHashCode(); 
     return hCode.GetHashCode(); 
    } 
} 

然後你可以再補充一個

.Distinct(new MyClassComparer()) 

的結果列表。服用點像(也許需要一些調整,現在不能測試):

dups = myList 
    .AsParallel() 
    .GroupBy(x => x.field1) 
    .Where(x => x.Count() > 1) 
    .Select(x => x.Key) 
    .ToList(); 

undupeds = 
    dups.Distinct(new MyClassComparer()); 

警告:這並擺脫重複的數據庫查詢後。

0
List<Fields> RemoveDuplicates(List<Fields> fields) 
    { 
     List<Fields> removedDuplicates = new List<Fields>(); 

     fields.ForEach(f => 
     { 
      if (removedDuplicates.FindAll(d => 
       d.Field1 == f.Field1 && 
       d.Field2 == f.Field2).Count == 0) 
      { 
       removedDuplicates.Add(f); 
      } 
     }); 

     return removedDuplicates; 
    } 

不知道這是否正是你要求的,但它應該創建一個新列表,其中只有原始列表中每個副本有一個「Fields」對象實例。

相關問題