是否有在.NET中自动排序的列表? [英] Is there a list that is sorted automatically in .NET?

查看:49
本文介绍了是否有在.NET中自动排序的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Layers的集合,其中有名字和颜色.我要做的是首先根据颜色对它们进行排序,然后根据其名称进行排序:

I have a collection of Layers where they have names and colors. What I want to do is to sort these first based on colors, then based on their names:

class Layer
{
    public string Name {get; set;}
    public LayerColor Color {get; set;}
}

enum LayerColor
{
    Red,
    Blue,
    Green
}

赞:

(red) layer2
(red) layer7
(blue) layer0
(blue) layer3
...

我当时正在查看SortedList,但这就像一个Dictionary,因此不允许重复项.

I was looking at SortedList but that acts like a Dictionary so doesn't allow for duplicate items.

我还使用了一个API,该API可以按创建顺序获取Layers的列表,因此我需要获取Layers的完整列表,以便按照自己的方式对它们进行排序.

Also I am using an API where I get the list of Layers by creation order, so I need to get the full list of Layers to sort them the way I want.

最终,Layers的列表将绑定到WPF UI,用户可以在其中添加新的图层,因此这就是为什么我希望内部列表始终被排序的原因,因为性能并不重要(数字的Layers少于一千).

Eventually the list of Layers will be binded to a WPF UI where the users will have the ability to add new Layers, so that's why I wanted the internal list to always be sorted as the performance is not important (the number of Layers are less than a thousand).

最后,通过以下内容访问我排序的Layers:

In the end the Layers I sorted will be accessed via something like this:

class Image
{
    public MySortedList<Layer> Layers {get; set;}
}

做到这一点的最佳方法是什么?

What's the best way to do this?

推荐答案

您要搜索吗? 通用SortedList 所以我错过了重复的部分,这使我同意起来有点困难.但是这是我要解决的方法:

So I missed the duplicate part which make it a little bit harder I agree. But here is how I would solve it:

var sortedList = new SortedList<LayerColor, SortedList<Layer, Layer>>();
var redSortedList = new SortedList<Layer, Layer>();
// Add all layers associated with the color red
sortedList.Add(LayerColor.Red, redSortedList);

这对您有用.另外,我更喜欢使用linq,但是如果您真的想要一个排序列表,那么我的解决方案很可能会起作用.

Will that work for you. Also, I would prefer to use linq but if you really want a sorted list my solution will most likely work.

最后一次尝试:):

public class YourClass
{
    private List<Layer> _layers;
    public List<Layer> Layers
    {
        get
        {
            _layers = _layers.OrderBy(y => y.LayerColor).ThenBy(y => y.Name).ToList();
            return _layers;
        }
        set
        {
            _layers = value;
        }
    }
}

请注意,我是直接在浏览器中编写代码,而没有在VS中测试(坐在OS X上),但是您可能会明白这一点.

Note that I'm writing directly in browser without testing it in VS (sitting on OS X), but you probably get the point.

这篇关于是否有在.NET中自动排序的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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