0

I analyzed code of malware written in C# and came across something unclear to me. The LINQ OrderBy method was applied on a char array. However, I was suprised about the lambda expression inside, which was similar to the one below.

var charArray = "abcdefghijk".ToCharArray();

string generatedString = new string(charArray
  .OrderBy(s => (random.Next(2) % 2) == 0)
  .ToArray());

I wonder how it works if the expression value is bool. It is also puzzling to me that if I put simple true or false values there instead, I always get the same string of "abcdefghijk" characters. Why is it always mixed up with this expression?

Dmitry Bychenko
  • 149,892
  • 16
  • 136
  • 186
fifuncio
  • 3
  • 1
  • Code is just showing how to convert an Character Array to a string. Much simpler to use string generatedString = string.Join("", charArray); – jdweng Jul 02 '20 at 20:55

1 Answers1

0

Booleans can be ordered - false comes before true. If you replace the lambda with an s => true or s => false, you give each character the same boolean value to be sorted by, so the original string order will be retained. With this lambda, you assign a random true or false value to each character, and the characters are shuffled.

Mureinik
  • 252,575
  • 45
  • 248
  • 283