c# - List 数组 排列 组合

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yuxuac/article/details/84783782

假设我们有以下x(3)个List(List1~3),每个List长度不固定,我们希望每次从这x(3)个List中各取一个值组合成一个x(3)个元素的数组,请打印出(返回)所有的可能:

using System.Collections.Generic;
using System.Linq;
using System;

namespace YourNameSpace
{
    class Program
    {
        static void Main(string[] args)
        {
            List<List<int>> listArray = new List<List<int>>()
            {
                new List<int>() { 0, 1, 2, 3 },
                new List<int>() { 0, 1 },
                new List<int>() { 0, 1, 2 },
            };

            var allCombinations = AllCombinationsOf(listArray);
            foreach (var combination in allCombinations)
            {
                Console.WriteLine(string.Join(", ", combination));
            }

            Console.ReadLine();
        }

        public static List<List<T>> AllCombinationsOf<T>(List<List<T>> sets)
        {
            var combinations = new List<List<T>>();

            foreach (var value in sets[0])
                combinations.Add(new List<T> { value });

            foreach (var set in sets.Skip(1))
                combinations = AddExtraSet(combinations, set);

            return combinations;
        }

        private static List<List<T>> AddExtraSet<T>
             (List<List<T>> combinations, List<T> set)
        {
            var newCombinations = from value in set
                                  from combination in combinations
                                  select new List<T>(combination) { value };

            return newCombinations.ToList();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/yuxuac/article/details/84783782