I'm trying to sort a List<string>
that contains a list of elements that are each numbers followed by letters. This is why each element can not simply be converted to an int. The list generates at run-time, but for example, the list might contain elements such as:
10 dog, 53 cow, 2 crow, 29 horse, 12 rabbit, 107 frog, 35 cat, 7 dragon
I've tried sorting like this:
public void Compare()
{
sortedList = sortedList.OrderBy(g => g).ToList();
}
Results:
10 dog, 107 frog, 12 rabbit, 2 crow, 29 horse, 35 cat, 53 cow, 7 dragon
Clearly it is sorting alphabetically because in this example 107 came before 12 with the "10"in 107 being smaller than 12. But I need to sort it in a way that it would return in the order of the numbers preceding the word.
I need this example to return:
2 crow, 7 dragon, 10 dog, 12 rabbit, 29 horse, 35 cat, 53 cow, 107 frog
I'm pretty new to coding, and this has me completely stumped. Any suggestions on how I can achieve my desired results?
OrderBy" function utilizes the default comparer for a string. That comparer is not necessarily going to return a sort order based on the ASCII code. For a list of all the different string comparers, see the article on MSDN.
Integer can be converted to String, but String cannot be converted to Integer. Integer is a numeric value, while String is a character value represented in quotes.
You can also add a LEFT(column,LOCATE(' ',column)) in the order by to group it by the letter(s) first, then the numbers.
Using this method split the given string into an array of tokens. The parseInt() method of the Integer class accepts a String value and converts it into an integer. Convert each element in the String array obtained in the previous step into an integer and store in into the integer array.
you can extract the data you want and then do the order by
var sorted = list
.Select(x => new
{
Splited = x.Split(),
Raw = x
}) //split the string and keep the raw value
.Select(x => new
{
Count = int.Parse(x.Splited[0]), // extract the number
Raw = x.Raw
})
.OrderBy(x => x.Count) //order by that number
.Select(x => x.Raw); //select raw value
lst = lst.OrderBy(x => Convert.ToInt32(x.Split()[0])).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With