簡體   English   中英

Linq然后無限期地跑

[英]Linq thenby running indefinitely

我有一個功能,只是打算以易於理解的方式打印頻繁項目集的字典。 目標是首先按字典鍵的大小排序,然后按數字列表的詞典順序排序。 問題出現在ThenBy語句中,因為注釋掉的“hello”將無限期地打印出來。 如果我改變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();
}

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

非常簡單的測試用例:

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

問題是ListComparer沒有檢查數組是否相同。 xy都傳遞了兩次相同的數組。 檢查xy是否相等將解決您的問題。

您的比較器不處理相同的項目。 如果項目相等,則兩個項目的順序決定哪個項目被認為是“更大”。 因此,比較器不是“反身的”。 反身是屬性排序算法所依賴的。

第一行應該是var larger = a.Count.CompareTo(b.Count); 相反,所以真正相等的列表將返回0而不是-11

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM