串集合在C#中置换 [英] Permutations of string collections in C#

查看:143
本文介绍了串集合在C#中置换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好像我被困再次与递归算法...

Seems like I'm stuck once again with recursive algorithms...

我的申请应该排序文件到不同的文件夹,根据由用户指定并根据由一个字符串象下面psented的子目录结构重新$ P $信息:

My application is supposed to sort files to different folders, according to the information specified by the user and according to a subfolder structure represented by a string like the following:

[ROOT] \ brand \ color \ material \ 

在结构上串重新present收藏的标记:

The tags in the structure string represent collections:

假设:

var brand = new List<string> { "Nike", "Adidas", "Reebok" };
var color = new List<string> { "red", "blue", "yellow", "black" };
var material = new List<string> { "leather", "fabric" };

var data = new List<List<string>>() { brand, color, material };

和什么我想要得到的是这样的:

And what I 'm trying to get is something like:

[ROOT]\Nike\red\leather
[ROOT]\Nike\red\fabric
[ROOT]\Nike\blue\leather
[ROOT]\Nike\blue\fabric
[ROOT]\Nike\yellow\leather
[ROOT]\Nike\yellow\fabric
[ROOT]\Nike\black\leather
[ROOT]\Nike\black\fabric
[ROOT]\Adidas\red\leather
[ROOT]\Adidas\red\fabric
[ROOT]\Adidas\blue\leather
[ROOT]\Adidas\blue\fabric
[ROOT]\Adidas\yellow\leather
[ROOT]\Adidas\yellow\fabric
[ROOT]\Adidas\black\leather
[ROOT]\Adidas\black\fabric
[ROOT]\Reebok\red\leather
[ROOT]\Reebok\red\fabric
[ROOT]\Reebok\blue\leather
[ROOT]\Reebok\blue\fabric
[ROOT]\Reebok\yellow\leather
[ROOT]\Reebok\yellow\fabric
[ROOT]\Reebok\black\leather
[ROOT]\Reebok\black\fabric

的问题是,不事先已知的数据标签(品牌,颜色,材料)和它们的顺序的量,因此需要递归。

The problem is that the amount of data tags (brand, color, material) and their order is not known in advance, hence the need for recursion.

你知道吗?

感谢你这么多提前!

推荐答案

下面是code。使用埃里克利珀。笛卡尔乘积。

Here is the code By Eric Lippert. Cartesian Product..

http://ericlippert.com/2010 / 06/28 /计算,一个笛卡尔积与 - LINQ /

public static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
    // base case: 
    IEnumerable<IEnumerable<T>> result = new[] { Enumerable.Empty<T>() };
    foreach (var sequence in sequences)
    {
        var s = sequence; // don't close over the loop variable 
        // recursive case: use SelectMany to build the new product out of the old one 
        result =
            from seq in result
            from item in s
            select seq.Concat(new[] { item });
    }
    return result;
}


var result = CartesianProduct(new List<List<string>>() {brand,color,material });


用法示例:


Usage Example:

var brand = new List<string> { "Nike", "Adidas", "Reebok" };
var color = new List<string> { "red", "blue", "yellow", "black" };
var material = new List<string> { "leather", "fabric" };

foreach (var row in CartesianProduct(new List<List<string>>() { brand, color, material }))
{
    Console.WriteLine(String.Join(",", row));
}

这篇关于串集合在C#中置换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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