[英]Compare two List<> on C#
我的問題是這樣的: C#列表比較
但唯一要注意的是:
我正在使用.NET Framework 2.0
因此,如何在C#框架2上比較兩個列表,並在項目不同的情況下返回布爾值?
instance == anotherone fails
instance.Equals(anotherone) fails.
編輯:
他們都是列表
編輯2
我正在嘗試比較列表值是否正確。 我可以對它們進行排序,為此。 問題是項目的計數或值是否更改。 例如:
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.
謝謝和親切的問候。
對於在計算交叉路口時要鏈接到的問題,您需要實現自己的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;
}
要處理它們是否具有相同頻率的相同項目:
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;
}
您可能應該在上面添加一些錯誤處理(第一個不為null,第二個不為null)。 請注意,由於您位於.NET 2.0中,因此無法使用HashSet<T>
。
如果要檢查列表中是否包含相同的項目(即,相同的項目以相同的順序):
public static bool ListsEqual<T>(List<T> list1, List<T> list2) {
if (list1.Count != list2.Count) return false;
for (int i = 0; i < list1.Count; i++) {
if (list1[i] != list2[i]) return false;
}
return true;
}
萊安德羅
您也可以使用我的開源比較.NET對象庫。 您可以將Config.IgnoreCollectionOrder設置為true。
https://comparenetobjects.codeplex.com/
[Test]
public void ComparerIgnoreOrderSimpleArraysTest()
{
var a = new String[] { "A", "E", "F" };
var b = new String[] { "A", "c", "d", "F" };
var comparer = new CompareLogic();
comparer.Config.IgnoreCollectionOrder = true;
comparer.Config.MaxDifferences = int.MaxValue;
ComparisonResult result = comparer.Compare(a, b);
Console.WriteLine(result.DifferencesString);
Assert.IsTrue(result.Differences.Where(d => d.Object1Value == "E").Count() == 1);
Assert.IsTrue(result.Differences.Where(d => d.Object2Value == "c").Count() == 1);
Assert.IsTrue(result.Differences.Where(d => d.Object2Value == "d").Count() == 1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.