Search code examples
c#linqpalindrome

When running a method that uses linq to get the palindromes from a string, why does SelectMany order the resulting strings?


So, i tried making a method that resulted in all the possible palindromes from a string, using linq. This is what the method is like:`

public IEnumerable<string> MakingPalindromesFromAString(string source)
        {
            return Enumerable
                .Range(1, source.Length)
                .SelectMany(length => Enumerable.Range(0, source.Length - length + 1)
                                                .Select(a => source.Substring(a, length)))
                                                .Where(b => b.SequenceEqual(b.Reverse()))
                .ToArray();
        }

Now, what I don't understand is why (or how) does SelectMany order the Enum? Because, for this example:

"xxyxxz"

the output (from how i tried to run the method by hand) should have been this:

z xxyxx xx x xyx x y xx x x

but instead it's this:

x x y x x z xx xx xyx xxyxx

Does anyone have any idea why this happens?


Solution

  • The first value of the range will be "1".

    So when you will call SelectMany the first value of length will be "1".

    The first value of the second range will be "0".

    So the select after that will make a substring from 0 to 1.

    And since your string is "xxyxxz" it seems coherent your first result is "x", isn't it ?