排序字典<object, List<int>> c#

usr*_*526 0 c# sorting dictionary

我想对一个对象列表进行排序,结构是一个 Dictionary<Object, List<int>>

字典中的项目将是

item_1, (2,2,3)
item_2, (1,3,4)
item_3, (2,3,4)
item_4, (1,2)
Run Code Online (Sandbox Code Playgroud)

一旦项目被排序,它们应该显示为

item_4, 1,2
item_2, 1,3,4
item_1, 2,2,3
item_3, 2,3,4
Run Code Online (Sandbox Code Playgroud)

所以,基本上我必须对列表中的第一项进行排序,然后是第二项,然后是第三项,使用 linq 实现这种解决方案的简单方法是什么

Ser*_*rvy 5

您需要的是一个自定义比较器,它可以根据该序列中的项目来比较一系列值,而不是基于对序列本身的引用(假设大多数序列不会覆盖默认的相等行为)。这是相当简单的:

public class SequenceComparer<T> : IComparer<IEnumerable<T>>
{
    private IComparer<T> comparer;
    public SequenceComparer(IComparer<T> comparer = null)
    {
        this.comparer = comparer ?? Comparer<T>.Default;
    }

    public int Compare(IEnumerable<T> x, IEnumerable<T> y)
    {
        using (var first = x.GetEnumerator())
        using (var second = y.GetEnumerator())
        {
            while (true)
            {
                var hasFirst = first.MoveNext();
                var hasSecond = second.MoveNext();
                if (hasFirst && !hasSecond)
                    return 1;
                if (hasSecond && !hasFirst)
                    return -1;
                if (!hasFirst && !hasSecond)
                    return 0;
                var comparison = comparer.Compare(first.Current, second.Current);
                if (comparison != 0)
                    return comparison;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用此比较器对集合中的项目进行排序:

var query = dictionary.OrderBy(pair => pair.Value, new SequenceComparer<int>());
Run Code Online (Sandbox Code Playgroud)

如果您希望序列中的项目根据它们的有序值进行排序,并且序列尚未排序,那么您可以将内部序列的排序添加到查询中:

var query = dictionary.OrderBy(pair => pair.Value.OrderBy(x => x), 
    new SequenceComparer<int>());
Run Code Online (Sandbox Code Playgroud)