And*_*rew 0 c# optimization list duplicates duplicate-removal
我需要根据另外两个列表创建一个列表.但似乎它不会删除重复项.
这种合并两个列表没有欺骗的有效方法吗?
List<String[]> blocksComparisonSet1 = new List<String[]>();
List<String[]> blocksComparisonSet2 = new List<String[]>();
//we will combine list1 and list2 into this one
List<String[]> blocksComparisonFinal = new List<String[]>();
//this is how I store data in each list
//if both values found, add both of them (partial functions, FYI)
String[] NA = new String[2]; //keep results
NA[0] = baseLine; //[0] for base
NA[1] = resultLine; //[1] for result
blocksComparisonSet1.Add(NA);
//if only one value found
String[] NA = new String[2]; //keep results
NA[0] = ""; //[0] for base
NA[1] = resultLine; //[1] for result
blocksComparisonSet1.Add(NA);
//This is where I merge lists and try to remove duplicates
if (blocksComparisonSet1.Count() > 0 || blocksComparisonSet2.Count() > 0)
//check if we have any values in out differences lists. if we do, merge them
{
blocksComparisonFinal.AddRange(blocksComparisonSet1);
//add records from one list to final list
blocksComparisonFinal.AddRange(blocksComparisonSet2);
//add records from second list to final list
blocksComparisonFinal = blocksComparisonFinal.Distinct().ToList();
//remove dublicates
}
Run Code Online (Sandbox Code Playgroud)
-
List1[] Example
string1 na
string2 na
string3 String1
string4 String7
string5 string8
na string9
na string2
Run Code Online (Sandbox Code Playgroud)
-
List2[] Example
na string2
na string5
String1 string3
String7 string4
string8 string5
string9 na
string2 na
Run Code Online (Sandbox Code Playgroud)
-
Final List[] must be:
na string9
na string2
na string5
string1 na
String1 string3
string2 na
string3 String1
string4 String7
string5 string8
String7 string4
string8 string5
string9 na
Run Code Online (Sandbox Code Playgroud)
var merge = blocksComparisonSet1.Union(
blocksComparisonSet2,
new ArrayEqualityComparer<string>()
).ToList();
Run Code Online (Sandbox Code Playgroud)
你需要一个自定义IEqualityComparer<string[]>.请参阅MSDN.
这是一个实现:
class ArrayEqualityComparer<T> : IEqualityComparer<T[]> {
public bool Equals(T[] x, T[] y) {
if(Object.ReferenceEquals(x, y)) {
return true;
}
if(x == null || y == null) {
return false;
}
return x.SequenceEqual(y);
}
public int GetHashCode(T[] x) {
if(x == null) {
return 0;
}
return x.Aggregate(
0,
(h, item) => h ^ (item != null ? item.GetHashCode() : 0)
);
}
}
Run Code Online (Sandbox Code Playgroud)