C# Remove duplicate logic
I have a List like this,
COL1 COL2 COL3
---- ---- -----
AA AB Some text
AA AC Some text
AA AB Some text
AB AB Some text
AB AC Some text
AA开发者_JAVA百科 AC Some text
I am looking for a fast and efficient logic in C# (perhaps in + LINQ) to remove duplicates in these two columns (COL1 , COL2 ) (Same like remove duplicates in Excel)
End result should be
AA AB Some text
AA AC Some text
AB AB Some text
AB AC Some text
Please advice
Use suggestion given by @Zerkms. For example, assuming your object type is 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());
This i the solution by Distinct
var query = (from record in MyList select record).Distinct();
精彩评论