2

I need to sort a string alphabetically. The most common solution I have found is to use linq:

var sortedString = unsortedString.OrderBy(c => c);

The problem I have with this solution is that the result is not a string. The result is an IOrderedEnumerable< char > which needs to be converted. This does not work:

var sortedString = unsortedString.OrderBy(c => c).ToString();
Tiny Tina
  • 85
  • 1
  • 7

2 Answers2

8

String is a sequence of characters. So

unsortedString.OrderBy(c => c)

returns sequence of ordered characters as well. I.e. IEnumerable<char>. You should create a new instance of string from these ordered characters:

var sortedString = new String(unsortedString.OrderBy(c => c).ToArray());

When you use ToString() on sequence of characters, you just get a type name of the sequence.

Sergey Berezovskiy
  • 224,436
  • 37
  • 411
  • 441
2

Another way is String.Concat which uses a StringBuilder:

string sortedString = String.Concat(unsortedString.OrderBy(c => c));

or String.Join (i prefer Concat without a delimiter):

string sortedString = String.Join("", unsortedString.OrderBy(c => c));
Tim Schmelter
  • 429,027
  • 67
  • 649
  • 891