我有一个函数,目的是以易于理解的方式打印出频繁项集的字典。目标是首先按照字典键的大小排序,然后按数字列表的词典顺序排序。问题在于ThenBy语句中的注释"hello"会无限打印。如果我更改ThenBy以不使用比较器而仅使用另一个int或string值,则可以正常工作,因此我显然做错了什么。
public static void printItemSets(Dictionary<List<int>, int> freqItemSet)
{
List<KeyValuePair<List<int>, int>> printList = freqItemSet.ToList();
printList = printList.OrderBy(x => x.Key.Count)
.ThenBy(x => x.Key, new ListComparer())
.ToList();
}
的代码如下:
public class ListComparer: IEqualityComparer<List<int>>, IComparer<List<int>>
{
public int Compare(List<int> a, List<int> b)
{
int larger = a.Count > b.Count ? 1: -1;
for (int i = 0; i < a.Count && i < b.Count; i++)
{
if (a[i] < b[i])
{
return -1;
}
else if (a[i] > b[i])
{
return 1;
}
else { }
}
return larger;
}
}
非常简单的测试案例:
int[] a = {1, 3, 5};
int[] b = { 2, 3, 5 };
int[] c = { 1, 2, 3, 5 };
int[] d = { 2, 5 };
int[] e = { 1, 3, 4 };
List<int> aL = a.ToList<int>();
List<int> bL = b.ToList<int>();
List<int> cL = c.ToList<int>();
List<int> dL = d.ToList<int>();
List<int> eL = e.ToList<int>();
Dictionary<List<int>, int> test = new Dictionary<List<int>, int>(new ListComparer());
test.Add(aL, 1);
test.Add(bL, 1);
test.Add(cL, 1);
test.Add(dL, 1);
test.Add(eL, 1);
var larger = a.Count.CompareTo(b.Count);
。话虽如此,这并不会导致你看到的问题。 - ServyIComparer
,而Dictionary
将使用IEqualityComparer
。由于这些方法不同,它们将被不同地实现。您不能同时使用单个方法来处理两者。 - Servy