计算两个列表中所有可能的项目对?

时间:2009-08-25 12:48:47

标签: c# .net linq combinations

我有两个数组:

string[] Group = { "A", null, "B", null, "C", null };

string[] combination = { "C#", "Java", null, "C++", null }; 

我希望返回所有可能的组合,例如:

{ {"A","C#"} , {"A","Java"} , {"A","C++"},{"B","C#"},............ }

应该忽略null。

1 个答案:

答案 0 :(得分:35)

Group.Where(x => x != null)
     .SelectMany(g => combination.Where(c => c != null)
                                 .Select(c => new {Group = g, Combination = c}));

可替换地:

from g in Group where g != null
from c in combination where c != null
select new { Group = g, Combination = c }