2

I never thought I would have to ask this... I need a way to mimic PHP's ksort function in C#.

Here's the problem... PHP does this...

PHP CODE

$arr = array(
    "tagValues" => "asdfasd",
    "email" => "asdfasd",
    "referrer" => "asdfasd",
    "tags" => "asdfasd",
);

echo "Base array \n\n";
print_r($arr);

ksort($arr);

echo "\n\nksort'ed array \n\n";
print_r($arr);

PHP OUTPUT

Base array 

Array
(
    [tagValues] => asdfasd
    [email] => asdfasd
    [referrer] => asdfasd
    [tags] => asdfasd
)


ksort'ed array 

Array
(
    [email] => asdfasd
    [referrer] => asdfasd
    [tagValues] => asdfasd
    [tags] => asdfasd
)

While if I do this in C#...

string[] sortedKeys = form.AllKeys.OrderBy(x => x).ToArray();

It comes out in a different order. tags will be before tagValues, as it rightfully should be. That is the true alphabetically order.

It's my understanding that ksort does some kind of case-sensitive ASCII work on the array and that's why it comes out in a different order.

How can I implement that in C#? Preferably with LINQ. Thanks!

For those interest in the backstory...

I'm basically trying to create an MD5 hash of input parameters sorted in alpha order per the FastSpring API. Their PHP snippet operates differently than I expected when I translated to C#, so the hash is always incorrect.

1 Answer 1

9

Keyword is StringComparer.Ordinal

string[] sortedKeys= form.AllKeys.OrderBy(x => x,StringComparer.Ordinal).ToArray();
1
  • Your gravatar made me thinking there is a layout issue on SO
    – zerkms
    Aug 29, 2012 at 22:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.