List<List<int>>的组合 [英] Combination of List&lt;List&lt;int&gt;&gt;

查看:42
本文介绍了List<List<int>>的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 List 类型的 List> 包含这个

I've a List of this type List> that contains this

List<int> A = new List<int> {1, 2, 3, 4, 5};
List<int> B = new List<int> {0, 1};
List<int> C = new List<int> {6};
List<int> X = new List<int> {....,....};

我想要所有这样的组合

1-0-6
1-1-6
2-0-6
2-1-6
3-0-6

等等.

根据您的说法,这可以使用 Linq 解决吗?

According to you is This possibile to resolve using Linq?

推荐答案

这个答案 我给了另一个问题:

It's quite similar to this answer I gave to another question:

var combinations = from a in A
                   from b in B
                   from c in C
                   orderby a, b, c
                   select new List<int> { a, b, c };

var x = combinations.ToList();

对于可变数量的输入,现在添加了泛型:

For a variable number of inputs, now with added generics:

var x = AllCombinationsOf(A, B, C);

public static List<List<T>> AllCombinationsOf<T>(params List<T>[] sets)
{
    // need array bounds checking etc for production
    var combinations = new List<List<T>>();

    // prime the data
    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();
}

这篇关于List<List<int>>的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆