Home > Mobile >  Custom sort of keyvaluepair
Custom sort of keyvaluepair

Time:05-31

I have a KeyValuePair<string, string> with following entries:

[adress_first_name, Andreas]
[adress_last_name, Test]
[adress_street, Berlinerstraße 2]
[adress_street_name, Berlinerstraße]
[adress_street_number, 2]
**[adress_street2, Tür 5]**
[adress_zipcode, 4600]

unfortunatly, the right order must be

[adress_first_name, Andreas]
[adress_last_name, Test]
[adress_street, Berlinerstraße 2]
**[adress_street2, Tür 5]**
[adress_street_name, Berlinerstraße]
[adress_street_number, 2]
[adress_zipcode, 4600]

Because of an external partner (who signs this list, and we need to verify the signature to make sure nothing has been manipulated with) the sort order must be like the second example.

What is the best way to do this using Linq? Of course, there are others, in that order. street2 is not the only example.

1

at the moment I order the list like here

2

CodePudding user response:

First order them by making address and address2 the same, then order by the key natural to split the tie:

.OrderBy(kv => (kv.Key.TrimEnd('2'), kv.Key))

This utilizes tuples sorting by all properties in order of appearance

You can also use the long form:

.OrderBy(kv => kv.Key.TrimEnd('2')).ThenBy(kv => kv.Key)

If you have more (address3, 4, 5..) you can add those to the trim. If you breach 9 and go to address10 you can OrderBy the trim of all numbers, then the Length of the key (so 9 sorts before 10), then the key itself to sort the numbers

CodePudding user response:

Use ordinal string comparer.

.OrderBy(kv => kv.Key, StringComparer.Ordinal);
  • Related