[ACCEPTED]-Is there a sorted collection type in .NET?-containers

Accepted answer
Score: 20

You might want to take a look at the Wintellect Power Collections. It 5 is available on CodePlex and contains quite 4 a few collections that are very helpful. The 3 OrderedBag collection in the project is 2 exactly what you are looking for. It essentially 1 uses a red-black tree to provide a pretty efficient sort.

Score: 13

Just to make EBarr's comment as answer, there is SortedSet<T> since 2 .NET 4.0. Of course it is a set, which means 1 you cannot have duplicates.

Score: 4

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

public class PositionDateComparer : IComparer<VehiclePosition>
{
    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 7 vehiclePositionsList.Sort(new PositionDateComparer()) whenever you want to sort the list before 6 accessing it. I realise that this might 5 not be as simple as a container which automatically 4 sorts every time you add a new object, but 3 for many (like me!) this might be enough 2 to do the job successfully without requiring 1 any additional libraries.

Score: 3

I would extend your own list class that, as 11 you mentioned, simply sorts after every 10 insert. Since your inserts are infrequent 9 the performance hit would be minimal, and 8 sorting a nearly sorted list is quick, in 7 any case. Extend the Generic List and override 6 the Add method to sort immediately. If performance 5 becomes an issue you can insert in place 4 to save some time. Furthermore you can queue 3 up your inserts to do a single traversal 2 insertion for all the values you want to 1 insert.

Score: 2

As I mentioned earlier today here, the C5 Generic Collection Library has 1 the proper container for you.

More Related questions