Search code examples
winformsc#-4.0sortedlist

Sort SortedList based on value C#


I have a sorted list

private SortedList _slSorted = new SortedList(); 

_slSorted has value Field which is of type class (actually 2 classes alternately dumped into them) having all the properties in them.

For example:

key:0 value:class1 object(having properties property 1 , property 2)

key:1 value:class2 object(having properties property 3 , property 4)

key:2 value:class1 object(having properties property 1 , property 2)

and so on..

I need to sort the sortedList based on either property 1 or property 3.

something like collect all the property values and sort them and rearrange

How can I do that?


Solution

  • You can create a new list that is sorted, by writing a class that implements IComparer<object>, and passing that to the LINQ OrderBy method. Like this:

    SortedList theList = new SortedList();
    // I assume you populate it here
    // Then, to sort:
    var sortedByValue = theList.Cast<object>().OrderBy(a => a, new ListComparer()).ToList();
    

    That will sort the items and create a new List<object> called sortedByValue. The ListComparer is shown below.

    Whereas this answers your question, I doubt that it's what you really want. But I don't know enough about your application, how you're using the SortedList, and what you want to do with the result above to give any kind of suggestion for doing it differently. I strongly suspect that you need to re-think your design, because what you're doing here is rather unusual.

    Here's the ListComparer.

    public class ListComparer: IComparer<object>
    {
        public int Compare(object x, object y)
        {
            if (x == null && y == null)
            {
                return 0;
            }
            if (x == null)
            {
                return -1;
            }
            if (y == null)
            {
                return 1;
            }
            if (x is Class1)
            {
                if (y is Class1)
                {
                    return (x as Class1).Prop1.CompareTo((y as Class1).Prop1);
                }
                // Assume that all Class1 sort before Class2
                return 1;
            }
            if (x is Class2)
            {
                if (y is Class2)
                {
                    return (x as Class2).Prop3.CompareTo((y as Class2).Prop3);
                }
                if (y is Class1)
                {
                    // Class1 sorts before Class2
                    return -1;
                }
                // y is not Class1 or Class2. So sort it last.
                return 1;
            }
            // x is neither Class1 nor Class2 
            if ((y is Class1) || (y is Class2))
            {
                return -1;
            }
            // Don't know how to compare anything but Class1 and Class2
            return 0;
        }
    }