C# 显示 IEnumerable 元素

C# Show IEnumerable elements

我有这个代码:

static void Main(string[] args)
        {
            IEnumerable<IEnumerable<int>> result = GetCombinations(Enumerable.Range(1, 3), 2);

        }

        static IEnumerable<IEnumerable<T>> GetCombinations<T>(IEnumerable<T> list, int length)
        {
            if (length == 1) return list.Select(t => new T[] { t });

            return GetCombinations(list, length - 1)
                .SelectMany(t => list, (t1, t2) => t1.Concat(new T[] { t2 }));
        }

问题是,如何显示 IEnumerable<IEnumerable<int>> result

中的所有元素
IEnumerable<IEnumerable<int>> resultList= GetCombinations(Enumerable.Range(1, 3), 2);
foreach (var result in resultList)
 {
    foreach(var element in result)
    {
        Console.WriteLine(element);
    }       
 }

只需使用 SelectMany 来展平结果。

IEnumerable<IEnumerable<int>> result = GetCombinations(Enumerable.Range(1, 3), 2);
foreach (var combination in resultList.SelectMany(x => x))
    Console.WriteLine(combination);

如果您打算迭代多次,您还应该添加 .ToLost() 以提高性能。

IEnumerable<IEnumerable<int>> result = GetCombinations(Enumerable.Range(1, 3), 2).ToList();