locked
sorting list of string which contains numbers and doubles/decimals RRS feed

  • Question

  • User-153404742 posted

    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.

    Monday, December 17, 2018 10:22 PM

All replies

  • User475983607 posted

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

    Monday, December 17, 2018 10:27 PM
  • User1724605321 posted

    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();
    

    No sure about your requirement , if misunderstand your requirement , please feel free to let me know .

    Best Regards,

    Nan Yu

    Tuesday, December 18, 2018 8:24 AM