mik*_*kel 13 .net c# linq arrays
我希望将两个字符串数组的内容组合成一个新列表,其中两个内容都连接在一起.
string[] days = { "Mon", "Tue", "Wed" };
string[] months = { "Jan", "Feb", "Mar" };
// I want the output to be a list with the contents
// "Mon Jan", "Mon Feb", "Mon Mar", "Tue Jan", "Tue Feb" etc...
Run Code Online (Sandbox Code Playgroud)
我该怎么做 ?当它只有两个数组时,以下工作并且很容易:
List<string> CombineWords(string[] wordsOne, string[] wordsTwo)
{
var combinedWords = new List<string>();
foreach (var wordOne in wordsOne)
{
foreach (string wordTwo in wordsTwo)
{
combinedWords.Add(wordOne + " " + wordTwo);
}
}
return combinedWords;
}
Run Code Online (Sandbox Code Playgroud)
但我希望能够传递不同数量的数组(即使用下面的签名方法)并使其仍然有效.
List<string> CombineWords(params string[][] arraysOfWords)
{
// what needs to go here ?
}
Run Code Online (Sandbox Code Playgroud)
或者其他一些解决方案会很棒.如果只使用Linq可以做到这一点,那就更好了!
Tho*_*que 16
你想要做的实际上是所有单词数组的笛卡尔积,然后用空格加入单词.Eric Lippert 在这里简单实现了Linq笛卡尔积.您可以使用它来实现CombineWords:
List<string> CombineWords(params string[][] arraysOfWords)
{
return CartesianProduct(arraysOfWords)
.Select(x => string.Join(" ", x))
.ToList();
}
Run Code Online (Sandbox Code Playgroud)
下面的代码适用于任意数量的数组(并在某种程度上使用 linq):
List<string> CombineWords(params string[][] wordsToCombine)
{
if (wordsToCombine.Length == 0)
return new List<string>();
IEnumerable<string> combinedWords = wordsToCombine[0].ToList();
for (int i = 1; i < wordsToCombine.Length; ++i)
{
var temp = i;
combinedWords = (from x in combinedWords from y in wordsToCombine[temp]
select x + " " + y);
}
return combinedWords.ToList();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3666 次 |
| 最近记录: |