C#删除重复的逻辑

时间:2011-05-12 04:00:03

标签: c#

我有一个像这样的列表,

COL1  COL2  COL3
    ----  ----  -----
    AA    AB    Some text  
    AA    AC    Some text
    AA    AB    Some text
    AB    AB    Some text
    AB    AC    Some text
    AA    AC    Some text

我在C#中寻找快速有效的逻辑(可能在+ LINQ中)来删除这两列(COL1,COL2)中的重复项(与删除Excel中的重复项相同)

最终结果应为

AA  AB Some text
AA  AC Some text
AB  AB Some text
AB  AC Some text

请咨询

2 个答案:

答案 0 :(得分:3)

使用@Zerkms提供的建议。例如,假设您的对象类型是MyRow:

public class MyRowComparer : IEqualityComparer<MyRow>
{
   public override bool Equals(MyRow r1, MyRow r2)
   {
      // adjust the logic as per your need e.g. case-insensitive etc
      return r1.Col1 == r2.Col1 && r1.Col2 == r2.Col2;
   }

   public override int GetHashCode(MyRow r)
   {
      // TODO: add null check etc
      return r.Col1.GetHashCode() ^ r.Col2.GetHashCode()
   }
}

IEnumerable<MyRow> myList = ...;
...
myList.Distinct(new MyRowComparer());

答案 1 :(得分:1)

这是Distinct的解决方案

var query = (from record in MyList select record).Distinct();
相关问题