0
var keyValuePairList = model.someDictionary.ToList();
keyValuePairList .OrderBy(r => r.Value);

The problem is sorting by alphanumeric values are not correct.

Output: CR1 CR10 CR11 CR2 CR20

Expected: CR1 CR2 CR10 CR11 CR20

Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
VKS
  • 487
  • 2
  • 7
  • 21
  • @TetsuyaYamamoto I looked many solutions including the possible duplicate you suggested above but in my case its List which makes it different. I can't figure it out. – VKS Aug 03 '18 at 03:40
  • 2
    @VijayendraShah - You **don't** have a `List` or a `List`, because that's not possible (apart from creating your own type...). You **do** (probably) have a `List>`, but that's not the point. Why don't you just do something like `yourDictionary.OrderBy(entry => MagicMethodThatWorksForLists(entry.Value))` where the "magic method" might be something like the `PadNumbers` method in the linked thread? – Corak Aug 03 '18 at 03:57
  • 1
    Are your inputs always "CR" followed by a stringified integer? If so, look at @ZevSpitz's answer. If not, is the pattern "two apha characters" followed by an integer, or maybe "N alpha characters" followed by an integer. If it's one of the latter two cases, you need to establish a sort order (alphas first then integer, or the other way around). Then you need to find a way to split the strings (a Regex would probably do it). Once you do that, sorting is pretty easy. – Flydog57 Aug 03 '18 at 05:09
  • 1
    @VijayendraShah - again the question: you seem to have found solutions for `List`, what makes you think those same solutions won't work on `List>`? (Or `Dictionary` or basically *any* `IEnumerable>`) – Corak Aug 03 '18 at 06:30
  • @Corak Thanks.....I followed your suggestion and Padding worked. Thanks!!!! – VKS Aug 04 '18 at 07:49

1 Answers1

0

If every string starts with two alphabetical characters, I would use the following:

keyValuePairList.OrderBy(r => int.Parse(r.Value.Substring(2)));

Otherwise, use a regular expression, as detailed in this answer.

var re = new  Regex(@"\d+$");
keyValuePairList.OrderBy(x => int.Parse(re.Match(x.Value).Value));
Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
  • Its not always CR it might be a normal string of any length or an alphanumeric string. – VKS Aug 03 '18 at 05:28
  • 1
    @VijayendraShah In the future, this is important information which should be included in the question. In any event, I refer you to my [answer](https://stackoverflow.com/a/51665173/111794) on the linked duplicate question. – Zev Spitz Aug 03 '18 at 08:09