如何在 C# 中对列表列表进行排序?

How to sort a List of Lists in C#?

我有一个列表列表,即 IList<IList<Result>>,我需要按 属性 DisplayOrder.

排序
IList<IList<Result>> results = new List<IList<Result>>();

results = validationResults.OrderBy(x => x.OrderBy(y => y.DisplayOrder)).ToList();

validationResults 值:

[
    [
        {
            "fieldName": "AccountName",
            "displayOrder": 5
        }
    ],
    [
        {
            "fieldName": "AccountNumber",
            "displayOrder": 6
        }
    ],
    [
        {
            "fieldName": "BankAddress",
            "displayOrder": 4
        }
    ]
]

期望值:

[
    [
        {
            "fieldName": "BankAddress",
            "displayOrder": 4
        }
    ],
    [
        {
            "fieldName": "AccountName",
            "displayOrder": 5
        }
    ],
    [
        {
            "fieldName": "AccountNumber",
            "displayOrder": 6
        }
    ] 
]

我试过了,但出现以下异常。

System.InvalidOperationException: Failed to compare two elements in the array. ---> System.ArgumentException: At least one object must implement IComparable. at System.Collections.Comparer.Compare(Object a, Object b) at System.Collections.Generic.ObjectComparer1.Compare(T x, T y) at System.Linq.EnumerableSorter2.CompareAnyKeys(Int32 index1, Int32 index2) at System.Collections.Generic.ComparisonComparer1.Compare(T x, T y) at System.Collections.Generic.ArraySortHelper1.InsertionSort(T[] keys, Int32 lo, Int32 hi, Comparison1 comparer) at System.Collections.Generic.ArraySortHelper1.IntroSort(T[] keys, Int32 lo, Int32 hi, Int32 depthLimit, Comparison1 comparer) at System.Collections.Generic.GenericArraySortHelper1.Sort(T[] keys, Int32 index, Int32 length, IComparer1 comparer) --- End of inner exception stack trace --- at System.Collections.Generic.GenericArraySortHelper1.Sort(T[] keys, Int32 index, Int32 length, IComparer1 comparer) at System.Array.Sort[T](T[] array, Int32 index, Int32 length, IComparer1 comparer) at System.Linq.EnumerableSorter2.QuickSort(Int32[] keys, Int32 lo, Int32 hi) at System.Linq.EnumerableSorter1.Sort(TElement[] elements, Int32 count) at System.Linq.OrderedEnumerable1.ToList() at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at Api.Controllers.ValidationController.ValidateFields(ValidateFieldsRequest validateFieldsRequest) in J:\Api\ValidationApi\ValidationApi\Controllers\ValidationController.cs:line 191

注意:我使用的是.net core 3.1

编辑:为了提高可读性,我添加了等价的JSON,以便其他人可以轻松理解和调试问题。是的,Result class 有一个 属性 DisplayOrder。我想对外部列表进行排序。 IList<Result> 始终只有一项。

展平列表,排序,然后投影回列表列表:

results = validationResults
    .SelectMany(x=>x) // Flatten
    .OrderBy(x=>x.DisplayOrder) // sort
    .Select(x=>new List<Result>{x}); // Project to list of lists

(我还没有检查这个编译,但希望你明白了)。

您可以用自己的列表包装列表,也可以将 IComparable 编写为扩展方法。