 # sorting list of string which contains numbers and doubles/decimalsRSS

## 2 replies

Last post Dec 18, 2018 08:24 AM by Nan Yu

• ### sorting list of string which contains numbers and doubles/decimals

I'm not sure what the fastest way to do this is but It's sorting the list in most cases when list is numbers only but if it has decimals, it's not sorting correctly.  So I have an object that returns the scores and how many occurances the score has but it's returned as string (the key).  How do I sort the list so it's sorted as integers and double comparison rather that strings?

<div>  var s = (from r in aa</div> <div>                             where r.Score != null && r.Score != ""</div> <div>                             orderby r.Score</div> <div>                             group r by r.Score into grp</div> <div>                             select new { key = grp.Key, cnt = grp.Count() }).OrderBy(x => x.key);</div> <div> </div> <div>                    var pl = s.OrderBy(c => c.key.Length).ThenBy(c => c.key).ToList();</div> <div></div> <div>so If I have ("0", "3", "2.5")....it won't sort in order of ("0", "2.5", "3")....I also need to keep the count linked with the actual key when sorting.</div>

aa = aa.OrderBy(x => x.Score).ToList();    --> this will sort it as string list of course which is not what I want.

• ### Re: sorting list of string which contains numbers and doubles/decimals

.NET is strongly typed and therefore requires a single type which should be decimal in this case.  You'll need to fix the design.

• ### Re: sorting list of string which contains numbers and doubles/decimals

Dec 18, 2018 08:24 AM|Nan Yu|LINK

Hi Inkaln,

Or try to convert to decimal when using OrderBy:

```var s = (from r in aa
where r.Score != null && r.Score != ""
orderby r.Score
group r by r.Score into grp
select new { Key = grp.Key, cnt = grp.Count() }).ToList();
var pl =  s.OrderBy(c => decimal.Parse(c.Key)).ToList();
```