如何生成一个名单,其中的元素的组合; T>在.NET 4.0中 [英] How to Generate Combinations of Elements of a List<T> in .NET 4.0

查看:140
本文介绍了如何生成一个名单,其中的元素的组合; T>在.NET 4.0中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题类似,但不完全相同的人回答<一href="http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n">here.

I have a question that is similar, but not identical, to the one answered here.

我想一个函数生成所有的 K 的从n个元素的列表元素-combinations。请注意,我找的组合,没有排列,而且我们需要不同的解决方案的 K 的(即硬编码的循环是一个禁忌)。

I would like a function generate all of the k-combinations of elements from a List of n elements. Note that I am looking for combinations, not permutations, and that we need a solution for varying k (i.e., hard-coding the loops is a no-no).

我要寻找一个解决方案,这是一个)优雅,和b)可以是codeD的VB10 / .NET 4.0。

I am looking for a solution that is a) elegant, and b) can be coded in VB10/.Net 4.0.

这意味着a)规定LINQ的解决方案是好的,B)那些使用C#收益命令都没有。

This means a) solutions requiring LINQ are ok, b) those using the C# "yield" command are not.

组合的顺序并不重要(即辞书,灰度code,有什么具备的,你)和优雅的赞成对性能,如果两者有冲突的。

The order of the combinations is not important (i.e., lexicographical, Gray-code, what-have-you) and elegance is favored over performance, if the two are in conflict.

(OCaml的和C#的解决方案<一href="http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n">here将是完美的,如果他们能为codeD中VB10。)

(The OCaml and C# solutions here would be perfect, if they could be coded in VB10.)

推荐答案

code在C#中产生的组合名单数组的 K 的元素:

Code in C# that produces list of combinations as arrays of k elements:

public static class ListExtensions
{
    public static IEnumerable<T[]> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        List<T[]> result = new List<T[]>();

        if (k == 0)
        {
            // single combination: empty set
            result.Add(new T[0]);
        }
        else
        {
            int current = 1;
            foreach (T element in elements)
            {
                // combine each element with (k - 1)-combinations of subsequent elements
                result.AddRange(elements
                    .Skip(current++)
                    .Combinations(k - 1)
                    .Select(combination => (new T[] { element }).Concat(combination).ToArray())
                    );
            }
        }

        return result;
    }
}

这里使用的集合初始化语法是VB 2010(

这篇关于如何生成一个名单,其中的元素的组合; T&GT;在.NET 4.0中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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