Need help understanding LINQ combinations

psriup 21 Reputation points
2021-05-25T12:25:58.407+00:00

I have this code from internet that finds all combinations of a list with LINQ. But I'm having hard time understanding in what order these LINQ methods execute and what is the result of each method call. Could someone please talk through the steps if not too much to ask.

public static class Combination
{
    public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        return k == 0 ?                              // if k = 0
            new[] { new T[0] } :                    // return empty Type array
            elements.SelectMany((element, i) => elements.Skip(i + 1)
            .Combinations(k - 1)
            .Select(combo => (new[] { element })
            .Concat(combo)));
    }
}

Thanks,

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Karen Payne MVP 35,596 Reputation points Volunteer Moderator
    2021-05-25T12:59:32.973+00:00

    Determine via the ternary operator ? if index is 0, if so return value on the left of : else start with flattening elements via SelectMany which leads to Skipping the parameter index which is from a recursive call to Combinations extension then adding combo to the array.

    Below I reformatted and changed variable names, the order should be clearer now via code indenting also.

    public static class Combination  
    {  
        public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int index)  
        {  
            return index == 0 ?   
                new[] { new T[0] } :   
                elements.SelectMany((element, indexer) =>   
                    elements.Skip(indexer + 1).Combinations(index - 1)  
                        .Select(combo => (new[] { element })  
                            .Concat(combo)));  
        }  
    }  
    

    99477-figure1.png

    Using the debugger to step into code can assist understanding code too.
    99370-figure2.png


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.