- Home /
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.
Answer by phil_me_up · Dec 17, 2015 at 08:48 PM
You probably want to use the IComparable interface and use the length of the string as your comparison (in your CompareTo function)
https://msdn.microsoft.com/en-us/library/system.icomparable(v=vs.110).aspx
Answer by Jessespike · Dec 17, 2015 at 09:14 PM
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[i].Length < stringList[j].Length)
{
string tempString = stringList[i];
stringList[i] = stringList[j];
stringList[j] = tempString;
}
}
}
return stringList;
}
If you're deploying to iOS, be aware that LINQ isn't necessarily fully supported and you can run in to JIT errors. It's been a while since I tried though and many issues may have been fixed, but I avoid it for mobile deployment as a general rule. I've also read that it's slower perfor$$anonymous$$g than other methods (again, particularly on mobile) but I've not run any of my own tests to prove this.
it's inconceivable performance would be an issue on this.
you're right that it's still a mystery whether Unity have "sorted out the mystery iOS-Linq problems".
oh well, it's only a $$anonymous$$or platform iOS and Unity only costs a few thousand bucks a year, we can't expect them to sweat such details as whether the code compiles
no no no no no your second method is a no-go ... bubble sort -.-
List<string> test = .... something .... ;
test.Sort(delegate(string x, string y){ return x.length - y.length });
im currently unsure if this would be the right order ... maybe this would be from longest to smallest word, if so: switch x.length - y.length to y.length - x.length
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Is it possible to name a list by a string variable? 2 Answers
Need help with switch case in order/timed 0 Answers
Update List<> in editor 0 Answers
How do I make a list of lists? 2 Answers