Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use custom sorting, based on the "Sort()" method of List<OwnObject>

In a previous post, I wanted to custom order a list of strings (List<string>). This is working fine now.

Now I would like a step further and sort a list of objects, having the mentioned strings as their name.

I thought this might be easy:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class OwnObject : IComparable
    public int CompareTo(object obj)
    {
        if (!(obj is OwnObject)) return 0;

        string s1 = this.Name;
        string s2 = (obj as OwnObject).Name;
        ...
    }
    ...
}

… and in another file, do something like:

...ToList().Sort(OwnObject.CompareTo);

However, it’s not that simple: I get the following compiler message:

Argument 1: cannot convert from 'method group' to 'System.Collections.Generic.IComparer<OwnObject>'.

I thought I was doing something similar like the CompareDinosByLength from the Microsoft learning website.

What am I doing wrong here?

>Solution :

If your OwnObject already implements IComparable (or IComparable<OwnObject>, then simply call the parameterless List<T>.Sort() method.

If you pass a method to Sort like in your example, then it must be compatible with the Comparison<T> delegate, which expects two strongly typed parameters. You can use it when T is not comparable or the default comparison is not preferable:

// Custom sorting by name if OwnObject does NOT have a proper IComparable implementation
ownObjectsList.Sort((x, y) => x.Name.CompareTo(y.Name));

Remark from the question author:

ToList().Sort() makes no sense: it should be:

resulting_list = ....ToList();
resulting_list.Sort();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading