dagda1
dagda1

Reputation: 28770

Unexpected Linq OrderBy

I have the following test which is failing:

[TestCase]
public void Should_order_numeric_suffix()
{
    var names = new List<string>
                    {
                        "Buisness Unit 7",
                        "Business Unit 1",
                        "Buisness Unit 3",
                        "Business Unit 6",
                        "Business Unit 4",
                        "Buisness Unit 2",
                        "Business Unit 5"
                    };

    List<string> ordered = names.OrderBy(x => x).ToList();

    Assert.That(ordered[0], Is.EqualTo("Business Unit 1"));
}

The actual order of the ordered List is:

Business Unit 2
Business Unit 3
Business Unit 7
Business Unit 1
Business Unit 4
Business Unit 5
Business Unit 6

Obviously it is ordering alphabetically correctly but I expected the numeric suffix to be ordered also.

Upvotes: 2

Views: 173

Answers (3)

Mentoliptus
Mentoliptus

Reputation: 2985

You can try to rewrite the query like this:

List<string> ordered = (from n in names
                        orderby n
                        select n).ToList<string>();

Upvotes: 0

Steav
Steav

Reputation: 1486

You are looking for natural sort order, which is not by default implemented in GroupBy You will need to implement a custom IComparer.

Of course those allready exist e.g:

http://www.interact-sw.co.uk/iangblog/2007/12/13/natural-sorting

http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html?showComment=1258020708758#c5034722582649839449

Upvotes: 1

Thomas Levesque
Thomas Levesque

Reputation: 292385

You have typos in your list, some entries spell "Buisness" instead of "Business"... and "Buisness" comes before "Business" in alphabetical order

Upvotes: 9

Related Questions