简体   繁体   English

Linq然后无限期地跑

[英]Linq thenby running indefinitely

I have a function that is simply meant to print out a dictionary of frequent item sets in an easy-to-understand fashion. 我有一个功能,只是打算以易于理解的方式打印频繁项目集的字典。 The goal is to order first by the size of the dictionary key and then by the lexicographical order of a list of numbers. 目标是首先按字典键的大小排序,然后按数字列表的词典顺序排序。 The issue arises in the ThenBy statement as the commented out "hello" will get printed indefinitely. 问题出现在ThenBy语句中,因为注释掉的“hello”将无限期地打印出来。 If I change the ThenBy to not use the comparer and simply use another int or string value, it works fine, so I'm clearly doing something wrong. 如果我改变ThenBy不使用比较器并只使用另一个int或字符串值,它工作正常,所以我显然做错了。

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();
}

The code for the ListComparer is as follows: ListComparer的代码如下:

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;
    }
}

VERY simple test case: 非常简单的测试用例:

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);

The issue is that ListComparer is not checking if the arrays are the same. 问题是ListComparer没有检查数组是否相同。 The same array is being passed in twice for both x and y . xy都传递了两次相同的数组。 Checking if x and y are equal will resolve your issue. 检查xy是否相等将解决您的问题。

Your comparer doesn't handle equal items. 您的比较器不处理相同的项目。 If the items are equal the order of the two items is what determines which is considered "larger". 如果项目相等,则两个项目的顺序决定哪个项目被认为是“更大”。 The comparer is thus not "reflexive". 因此,比较器不是“反身的”。 Being reflexive is a property sorting algorithms rely on. 反身是属性排序算法所依赖的。

The first line should be var larger = a.Count.CompareTo(b.Count); 第一行应该是var larger = a.Count.CompareTo(b.Count); instead, so that truly equal lists will return 0 rather than either -1 or 1 . 相反,所以真正相等的列表将返回0而不是-11

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM