Is there a sorted collection type in .NET?

前端 未结 7 1663
夕颜
夕颜 2020-12-01 08:19

I\'m looking for a container that keeps all its items in order. I looked at SortedList, but that requires a separate key, and does not allow duplicate keys. I could also j

7条回答
  •  温柔的废话
    2020-12-01 08:41

    If you just want to stick with the standard collections then the Sort(IComparer<>) function of the List<> class is one that often gets ignored. All you need to do is create a suitable Comparer<> for your objects. For example:

    public class PositionDateComparer : IComparer
    {
        public int Compare(VehiclePosition x, VehiclePosition y)
        {
            if (x.DateTime == DateTime.MinValue)
            {
                if (y.DateTime == DateTime.MinValue)
                {
                    // If x is null and y is null, they're
                    // equal. 
                    return 0;
                }
    
                // If x is null and y is not null, y
                // is greater. 
                return -1;
            }
    
            // If x is not null...
            //
            if (y.DateTime == DateTime.MinValue)
            // ...and y is null, x is greater.
            {
                return 1;
            }
    
            // ...and y is not null, compare the dates
            //
            if (x.DateTime == y.DateTime)
            {
                // x and y are equal
                return 0;
            }
    
            if (x.DateTime > y.DateTime)
            {
                // x is greater
                return 1;
            }
    
            // y is greater
            return -1;
        }
    }
    

    Then just perform a vehiclePositionsList.Sort(new PositionDateComparer()) whenever you want to sort the list before accessing it. I realise that this might not be as simple as a container which automatically sorts every time you add a new object, but for many (like me!) this might be enough to do the job successfully without requiring any additional libraries.

提交回复
热议问题