Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a list with two parameters using CompareTo

I am presently sorting a C# list using the 'CompareTo' method in the object type contained in the list. I want to sort ascendingly all items by their WBS (Work Breakdown Structure) and I can manage this very well using the following code:

        public int CompareTo(DisplayItemsEntity other)
        {
            string[] instanceWbsArray = this.WBS.Split('.');
            string[] otherWbsArray = other.WBS.Split('.');

            int result = 0;

            for (int i = 0; i < maxLenght; i++)
            {
                if (instanceWbsArray[i].Equals(otherWbsArray[i]))
                {
                    continue;
                }
                else
                {    
                    result = Int32.Parse(instanceWbsArray[i]).CompareTo(Int32.Parse(otherWbsArray[i]));
                    break;
                }
            }
            return result;
        }

Now, I would like to be able to sort considering more than one parameter, as in the project name alphabetically, before considering the second which would be the WBS. How can I do this?

like image 330
JF Beaulieu Avatar asked Apr 23 '26 05:04

JF Beaulieu


2 Answers

I don't know the details of your class, so I'll provide an example using a list of strings and LINQ. OrderBy will order the strings alphabetically, ThenBy will order them by their lengths afterwards. You can adapt this sample to your needs easily enough.

var list = new List<string>
{
    "Foo",
    "Bar",
    "Foobar"
};
var sortedList = list.OrderBy(i => i).
    ThenBy(i => i.Length).
    ToList();
like image 86
Mir Avatar answered Apr 24 '26 17:04

Mir


What we generally do in cases like yours is this:

public int CompareTo( SomeClass other )
{
    int result = this.SomeProperty.CompareTo( other.SomeProperty );
    if( result != 0 )
        return result;
    result = this.AnotherProperty.CompareTo( other.AnotherProperty );
    if( result != 0 )
        return result;
    [...]
    return result;
}
like image 39
Mike Nakis Avatar answered Apr 24 '26 19:04

Mike Nakis