Search code examples
c#listsortingcompareto

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?


Solution

  • 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();