hs2d
hs2d

Reputation: 6199

C# LINQ order by error

Hei, i think order by is ordering things wrongly. Example code:

static void Main()
{            
    // Create a delicious data source.
    string[] fruits = { "äax", "ääü", "äbü" };

    // Query for ascending sort.
    IEnumerable<string> sortAscendingQuery =
        from fruit in fruits
        orderby fruit //"ascending" is default
        select fruit;       

    // Execute the query.
    Console.WriteLine("Ascending:");
    foreach (string s in sortAscendingQuery)
    {
        Console.WriteLine(s);
    }
}

And the result:

Ascending:
ääü
äax
äbü

The right order should be: äax äbu ääü

Anybody encountered this error before?

Upvotes: 2

Views: 2120

Answers (2)

Xhalent
Xhalent

Reputation: 3954

This linq returns the correct results - you need specify the string comparison to use.

foreach (string s in fruits.OrderBy(s=>s, StringComparer.OrdinalIgnoreCase ) )
{
  Console.WriteLine(s);
}

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503889

That's going to use the default implementation of IComparer<string>. That's a culture-sensitive comparison, which I believe is why it's deeming "ääü" as coming before "äax".

Were you expecting an ordinal comparison? If so, you can specify the comparer explicitly, but not in a query expression:

IEnumerable<string> sortAscendingQuery = fruits
    .OrderBy(fruit => fruit, StringComparer.Ordinal);

If that's not what you're looking for, please explain what sort of comparison you need.

Upvotes: 8

Related Questions