0

I'm wanting to sort this array by length but how will I do that? I searched the web for a while but couldn't find anything. The code is supposed to sort an array given at random by each strings length in the string array, but I can't get anyway of declaring how I want it to sort.

public class Kata
{
  public static string[] SortByLength (string[] array)
  {
    Array.Sort(array);
    return array;
  }
}
1
  • 2
    what you want is OrderBy Commented Jul 18, 2020 at 17:58

3 Answers 3

2

Well, in order to sort the array in place you should provide rule of sorting:

  Array.Sort(array, (x, y) => x.Length.CompareTo(y.Length));   

The method can be

  public static string[] SortByLength (string[] array) {
    //TODO: validate array and its items here; they must be not null

    Array.Sort(array, (x, y) => x.Length.CompareTo(y.Length));

    return array;
  } 
Sign up to request clarification or add additional context in comments.

Comments

1

Use linq...

public static string[] SortByLength (string[] array) =>
    array.OrderBy( x => x?.Length ?? 0 ).ToArray();

Comments

0

Dude, this is how it should work.

Array.Sort(array, StringComparer.InvariantCulture);

1 Comment

Does not sort by length

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.