Reputation: 5619
I was posed this trivia question and thought it was rather simplistic. The person asked me to explain why this list didn't sort alphabetically. I thought it a trick question till I threw it into a little stub project and they were right...no trick it doesn't sort alphabetically. I Googled and everything I read said Sort() would work the way I expect. So edjumakate me geniuses. I obviously don't have the answer.
string str_animals = "hyena, cat, elephant, dog, iguana";
List<string> lst_animals = new List<string>(str_animals.Split(','));
lst_animals.Sort();
After the sort my list is: cat, dog, elephant, iguana, hyena???? Hyena & iguana are out of order?
MSDN says "This method uses Array.Sort, which uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal" but hyena and iguana are not equal so I don't see that unstable sort would matter.
What am I missing?
Thank You
Upvotes: 0
Views: 123
Reputation: 5280
Simply use
List<string> lst_animals = new List<string>(str_animals.Split(", "));
The space in ",_"
is important!
Like it's been pointed out by others only splitting by a comma will have the split string have a prefixed space. And a space comes before letters regarding sorting.
Upvotes: 0
Reputation: 56934
You're using Split, which splits the string into different strings. Hyena is the first one, and has no preceding space. The others all have a space in front, which affects your sorting.
therefore, you should remove the leading space by trimming the strings after you've splitted the original string.
var animals = str_animals.Split(',').Select (a => a.Trim());
Upvotes: 1
Reputation: 69362
You need to trim the values after splitting because the whitespace will throw off the sort (making hyena
come after iguana
since hyena
does not start with a whitespace).
List<string> lst_animals = new List<string>(str_animals.Split(',').Select(x => x.Trim()));
Upvotes: 5