Ordering a string list in size order

Hello,

I have a List<string> and it contains a lot of strings of different lengths. I need to re order the list in size order so the smallest strings are first, and then the bigger ones last.
Does anyone know how i can do this?

Any help is greatly appreciated, thanks.

You probably want to use the IComparable interface and use the length of the string as your comparison (in your CompareTo function)

IComparable Interface (System) | Microsoft Learn

There are several ways. Implementing IComparable would work. Another way is to use Linq to sort:

using System.Linq;

List<string> SortByLength(List<string> stringList)
{
	var sortedStringList = stringList
		.OrderBy(n => n.Length)
		.ToList();

	return sortedStringList;
}

You’d just need to do this:

 myStringList = SortByLength(myStringList);

Another way, which isn’t very pretty, but would work without Linq is this:

List<string> SortStrings(List<string> stringList)
{
	for(int i = 0; i < stringList.Count; i++)
	{
		for (int j = 0; j < stringList.Count; j++)
		{
			if (stringList*.Length < stringList[j].Length)*
  •  	{*
    

_ string tempString = stringList*;_
_ stringList = stringList[j];
stringList[j] = tempString;
}
}
}*_

* return stringList;*
}