巧妙地连接两套

时间:2013-06-23 17:47:10

标签: c#-4.0

说我有两套

var Set1 = new[] { "A", "B", "C" };
var Set2 = new[] { "1", "2", "3" };

连接这两套通常我做

foreach (string itm1 in Set1 )
{
     foreach (string itm2 in Set2)
     {
         Console.WriteLine(itm1 + itm2);
     }
}

是否有任何LINQ风格获得相同的结果?

2 个答案:

答案 0 :(得分:2)

var strs = Set1.SelectMany(s1 => Set2.Select(s2 => s1 + s2))
foreach(string s in strs)
{
    Console.WriteLine(s);
}

或者使用查询语法:

var strs = from s1 in Set1
           from s2 in Set2
           select s1 + s2;

答案 1 :(得分:0)

尝试

 var concatSet =Set1
                .SelectMany(
                             item => Set2,
                             (i1, i2) => (i1 + i2)
                           );