Caleb Jares
Caleb Jares

Reputation: 6307

OrderBy without lambda for simple IEnumerables

Is there a simpler way to write the following? I.E., without the lambda.

var strings = new[] { "Alabama", "Mississippi", "Louisiana" };
var ordered = strings.OrderBy(x => x);

Seems like it should be possible, since string implements IEquatable<string>.

Upvotes: 1

Views: 606

Answers (2)

dana
dana

Reputation: 18125

For .NET 7 or higher, use Order.

var strings = new[] { "Alabama", "Mississippi", "Louisiana" };
var ordered = strings.Order();

dotnet/runtime#67194

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415725

It's IComparable that matters more thanIEquatable here, but it is possible:

Array.Sort(strings);

This works because strings is already an array. Since you asked for any IEnumerable:

var ary = strings.ToArray();
Array.Sort(ary);

Note the extra variable is also important in this second sample, because Array.Sort() sorts the actual object passed without returning the results, and calling .ToArray() created a new array that was then thrown away. Without the extra variable, you lose your work.

There is a similar sort method on the List<T> object you can use, as well.

You can also make your own extension method for this:

public static class MyExtensions
{
    public static IOrderedEnumerable<T> Sort(this IEnumerable<T> items) where T : IComparable
    {
        return items.OrderBy(i => i);
    }
}

And now you could just say:

var ordered = strings.Sort();

Upvotes: 6

Related Questions