1

I’m trying to convert from this answer the code:

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 }));
}

Into a list of strings. For example I want this output {1,2} {1,3} to convert it to "1,2","1,3" (this is 2 seperate string) but I cant get it. I cant even understand how I can read the results of the above function. this is my code:

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);

In the end all the results i will add them on a List with all the possible unique combinations For example for the numbers {1,2,3} i want this List: '1','2','3','1,2','1,3','2,3','1,2,3'

This is my code right now:

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);                            
 }
SSD
  • 1,373
  • 2
  • 13
  • 20
CDrosos
  • 2,418
  • 4
  • 26
  • 49

2 Answers2

2

You can try first joining the results of the inner IEnumerables

var combinations = GetKCombs(numbers, 2).Select(c => string.Join(",", c));

and then concatenating them into a single string

var combinationString = string.Join("; ", combinations); // "1,2; 1,3"

Based on your edits -- if I got you right -- you can try doing

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();
1

Try

    var stringCombinations = string.Join(",", combinations.Select(j => $@"""{string.Join(",", j)}"""));

It prints exactly the output you want.

taquion
  • 2,667
  • 2
  • 18
  • 29
  • i have update my question cause i think i haven't point exactly what i want. I want the combinations to be added an a list not to be combined to another string. – CDrosos Feb 25 '18 at 12:56