排序字典< object,List< int>>C# [英] sort a dictionary <object, List<int>> c#

查看:47
本文介绍了排序字典< object,List< int>>C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to sort a list of objects, The structure is a Dictionary<Object, List<int>>

项应为

item_1, (2,2,3)
item_2, (1,3,4)
item_3, (2,3,4)
item_4, (1,2)

项目排序后,它们应显示为

once the items are sorted they should appear as

item_4, 1,2
item_2, 1,3,4
item_1, 2,2,3
item_3, 2,3,4

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

so, essentially I have to sort on the first item in the list, then the second item, then the 3rd items, what would be an easy way of implementing such a solution using linq

推荐答案

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

What you need is a custom comparer that can compare a sequence of values based on the items in that sequence, rather than based on the reference to the sequence itself (given that most sequences don't override the default equality behavior). This is fairly straightforward:

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

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

You can then order the items in your collection using this comparer:

var query = dictionary.OrderBy(pair => pair.Value, new SequenceComparer<int>());

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

If you want the items in the sequence to sort based on their ordered values, and the sequences are not already ordered, then you can add an ordering of the inner sequences into the query:

var query = dictionary.OrderBy(pair => pair.Value.OrderBy(x => x), 
    new SequenceComparer<int>());

这篇关于排序字典&lt; object,List&lt; int&gt;&gt;C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆