Is there a list that is sorted automatically in .NET?

前端 未结 8 1178
轻奢々
轻奢々 2021-02-05 04:00

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:



        
8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 04:45

    Did you search for it? Generic SortedList and 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>();
    var redSortedList = new SortedList();
    // Add all layers associated with the color red
    sortedList.Add(LayerColor.Red, redSortedList);
    

    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.

    Last try:) :

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

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

提交回复
热议问题