Create all combinations of n*m values

后端 未结 2 1880
有刺的猬
有刺的猬 2020-12-05 15:47

Say I have a data structure of IEnumerable> like this:

{
    { A, B }
    { 1, 2, 3 }
    { Z }
}
2条回答
  •  鱼传尺愫
    2020-12-05 16:10

    private static IEnumerable> GetAllCombinations(IEnumerable> a)
        {
            if (!a.Skip(1).Any())
            {
                return a.First().Select(x => new[] { x });
            }
    
            var tail = GetAllCombinations(a.Skip(1)).ToArray();
            return a.First().SelectMany(f => tail.Select(x => new[] { f }.Concat(x)));
        }
    

提交回复
热议问题