Question

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.

Was it helpful?

Solution

Keyword is StringComparer.Ordinal

string[] sortedKeys= form.AllKeys.OrderBy(x => x,StringComparer.Ordinal).ToArray();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top