2017-10-12 99 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”对象实例。

相关问题