将2个或更多数组连接成新列表中的唯一组合 [英] Concatenate 2 or more arrays into unique combinations in new list
问题描述
我正在研究一个可以有2个或更多字符串值数组的问题.
I am working on a problem where I have can have 2 or more arrays of string values.
从第一个数组开始,我需要获取每个值并将下一个数组的第一个值与第三个数组中的第一个值连接起来,依此类推,直到所有可能的组合都组合在一起.
Starting with the first array, I need to take each value and concatenate the first value of the next array and the first from the third and so on until all possible combinations have been combined.
示例:
Array1 {'A', 'B'}
Array2 {'C', 'D', 'E'}
Array3 {'F', 'G', 'H'}
输出应为
Row 1 = A, C, F
Row 2 = A, C, G
Row 3 = A, C, H
Row 4 = A, D, F
Row 5 = A, D, G
Row 6 = A, D, H
,依此类推,直到完成所有组合.在这种情况下,将是18种组合.
and so on until all combinations are completed. In this case it would be 18 combinations.
我以前使用字符串串联来组合值,但从未在像这样的过程中使用过,在此过程中数组的数目可能会发生变化,并且其中的项目数会产生这种类型的输出.
I have used string concatenation before to combine the values, but never in a process like this where the number of arrays could change and the number of items within to produce this type of output.
推荐答案
public static partial class MyExtensions
{
//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;
}
}
这篇关于将2个或更多数组连接成新列表中的唯一组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!