Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OrderBy numbers that are strings (cannot convert to int)

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?

like image 236
Ibanezowns Avatar asked Jun 10 '15 11:06

Ibanezowns


People also ask

Does OrderBy work on string?

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.

Can integers be strings?

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.

How order a string contains numbers in SQL?

You can also add a LEFT(column,LOCATE(' ',column)) in the order by to group it by the letter(s) first, then the numbers.

How do I sort an integer into a string?

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.


2 Answers

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
like image 144
Hamid Pourjam Avatar answered Nov 18 '22 22:11

Hamid Pourjam


lst = lst.OrderBy(x => Convert.ToInt32(x.Split()[0])).ToList();
like image 45
Vanest Avatar answered Nov 18 '22 23:11

Vanest