Lea*_*dro 0 c# arraylist object .net-2.0
我的问题是这样的: c#list compare
但唯一需要注意的是:
我正在使用.NET Framework 2.0
那么如何在C#framework 2上比较两个列表并在项目不同时返回一个布尔值呢?
instance == anotherone fails
instance.Equals(anotherone) fails.
Run Code Online (Sandbox Code Playgroud)
编辑:
他们都是List
编辑2
我正在尝试比较列表值是否正确.我可以对它们进行排序,np.问题是如果项目的计数或值发生变化.例如:
List1->Item1 = "A"
List1->Item2 = "B"
List2->Item1 = "B"
List2->Item2 = "A"
//must return true
List1->Item1 = "A"
List1->Item2 = "B"
List2->Item1 = "B"
List2->Item2 = "C"
//must return false
List1->Item1 = "A"
List1->Item2 = "B"
List2->Item1 = "B"
List2->Item2 = "A"
List2->Item3 = "A"
//must return false, etc.
Run Code Online (Sandbox Code Playgroud)
谢谢和亲切的问候.
对于您在计算交叉点时链接的问题,您需要实现自己的版本Intersect
.这应该让你开始:
List<T> Intersect<T>(List<T> first, List<T> second) {
Dictionary<T, T> potential = new Dictionary<T, T>();
foreach (var item in first) {
potential.Add(item, item);
}
List<T> intersection = new List<T>();
foreach (var item in second) {
if (potential.Remove(item)) {
intersection.Add(item);
}
}
return intersection;
}
Run Code Online (Sandbox Code Playgroud)
要处理它们是否具有相同频率的相同项目:
bool AreSameAsMultiSets(List<T> first, List<T> second) {
Dictionary<T, int> counts = new Dictionary<T, int>();
foreach (var item in first) {
if (!counts.ContainsKey(item)) {
counts.Add(item, 0);
}
counts[item] = counts[item] + 1;
}
foreach (var item in second) {
if (!counts.ContainsKey(item)) {
return false;
}
counts[item] = counts[item] - 1;
}
foreach (var entry in counts) {
if (entry.Value != 0) {
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
您应该在上面添加一些错误处理(首先不是null,第二个不是null).请注意,HashSet<T>
由于您使用的是.NET 2.0 ,因此无法使用.
归档时间: |
|
查看次数: |
3904 次 |
最近记录: |