1

我试图弄清楚如何使用 C# 创建一个来自 3 个单独列表的串联列表。例如:

 List 1: Ugly, Pretty
 List 2: Dogs, Carts, Pigs
 List 3: Rock, Suck

输出:

 Ugly Dogs Rock
 Ugly Dogs Suck
 Ugly Cats Rock
 Ugly Cats Suck
 Ugly Pigs Rock
 Ugly Pigs Suck
 Pretty Dogs Rock
 Pretty Dogs Suck
 Pretty Cats Rock
 Pretty Cats Suck
 Pretty Pigs Rock
 Pretty Pigs Suck

我知道这只是嵌套循环,但我不知道的部分是如何为每个列表使用列表字符串。

4

3 回答 3

4

不是笛卡尔积吗?

var r = from i1 in list1
        from i2 in list2
        from i3 in list3
        select new { i1, i2, i3 };
        // or String.Format("{0} {1} {2}", i1, i2, i3);
于 2012-12-16T22:20:38.830 回答
4
var list = from s1 in list1
           from s2 in list2
           from s3 in list3
           select s1 + " " + s2 + " " + s3;
于 2012-12-16T22:21:02.993 回答
3
List<string> list1 = new List<string>(){ "Ugly", "Pretty"};
List<string> list2 = new List<string>(){ "Dogs", "Carts", "Pigs"};
List<string> list3 = new List<string>(){ "Rock", "Suck"};

var result = from s1 in list1
             from s2 in list2
             from s3 in list3
             select new[] { s1, s2, s3 };

foreach (var item in result)
{
    Console.WriteLine(String.Join(",", item));
}

如果您正在寻找更通用的解决方案,不仅是 3 个列表,您可以尝试 Eric Lippert 的解决方案

foreach (var item in new[] { list1, list2, list3 }.CartesianProduct())
{
    Console.WriteLine(String.Join(",", item));
}

public static partial class MyExtensions
{
    // Eric Lippert’s Blog
    // Computing a Cartesian Product with LINQ
    // http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx
    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;
    }
}
于 2012-12-16T22:24:24.323 回答