Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom sort of keyvaluepair

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading