【发布时间】:2018-08-04 19:13:10
【问题描述】:
我正在尝试从this answer 转换代码:
static IEnumerable<IEnumerable<T>> GetKCombs<T>(IEnumerable<T> list, int length) where T : IComparable
{
if (length == 1) return list.Select(t => new T[] { t });
return GetKCombs(list, length - 1)
.SelectMany(t => list.Where(o => o.CompareTo(t.Last()) > 0),
(t1, t2) => t1.Concat(new T[] { t2 }));
}
进入一个字符串列表。例如,我希望此输出 {1,2} {1,3} 将其转换为“1,2”、“1,3”(这是 2 个单独的字符串),但我无法得到它.我什至无法理解如何读取上述函数的结果。这是我的代码:
int[] numbers = ListEditText.Text.Split(',').Select(x => int.Parse(x)).ToArray();
var combinations = GetKCombs(numbers, 2);
stringCombinations = combinations.Select(j => j.ToString()).Aggregate((x, y) => x + "," + y);
最后,我会将所有结果添加到列表中,其中包含所有可能的唯一组合 例如对于数字 {1,2,3} 我想要这个列表: '1','2','3','1,2','1,3','2,3','1,2,3'
这是我现在的代码:
List<string> stringCombinations = new List<string>();
for (int i = 0; i < numbers.Count(); i++)
{
combinations = GetKCombs(numbers, i + 1).Select(c => string.Join(",", c));
stringCombinations.AddRange(combinations);
}
【问题讨论】:
-
string.Join可以帮你得到你想要的:combinations.Select(x => string.Join(",", x))