我正试图从这个答案中转换出代码:
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’,“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);
}
您可以尝试首先加入内部IENumable的结果
var combinations = GetKCombs(numbers, 2).Select(c => string.Join(",", c));
然后将它们连接成一个字符串
var combinationString = string.Join("; ", combinations); // "1,2; 1,3"
根据您的编辑 - 如果我做对了 - 您可以尝试做
var combinationStrings =
numbers
.SelectMany((_, i) =>
GetKCombs(numbers, i + 1) // get combinations for each 'length'
.Select(c => string.Join(",", c))) // join them to a string
.ToList();
尝试
var stringCombinations = string.Join(",", combinations.Select(j => $@"""{string.Join(",", j)}"""));
它完全打印您想要的输出。