Click here to Skip to main content
16,004,587 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hey! I really need some help.
I have a function for generating combinations. Here it is
C#
public 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 }));
}


usage is:
C#
var result = GetKCombs(new int[] {1,2,3,4,5},3);

Problem is following: i want to convert var to List<string>, and .ToList() doesn`t work properly.
Please, help.

What I have tried:

Well, i`ve tried to do use method .ToList():
result.ToList()
but it contains something strange.
Secondly, i`ve written following:
List<string> vectors = new List<string>();
foreach (var res in result)
vectors.Add(res.ToString());
but it didn`t work properly too.
Posted
Updated 23-Jul-16 2:58am
Comments
sankholia 23-Jul-16 7:16am    
I am not sure what you are trying to achieve. If you can elaborate your problem statement it would be easier to answer or to suggest if an alternate solution exists.
Ralf Meier 23-Jul-16 7:16am    
Sorry - I don't understand your goal.
Try to explain, what you want to achieve with some examples ...
Member 12153456 23-Jul-16 7:23am    
okay, i`ll try to be clear
we have, for example, a set {1,2,3,4,5} and i want to generate all combinations of length 3 by using function GetKComb in following way:
var result = GetKComb(new int[] {1,2,3,4,5},3)
result consists of something i dont understand what but in result there are 10 objects. I want get from result strings of 3-length to a List<string>, but i don't know how.
Member 12153456 23-Jul-16 7:25am    
and i want List<string> to consist of 10 strings which are "{1,2,3}", "{1,2,4}" and etc.

1 solution

well, solution was simple:
C#
List<string> vectors = new List<string>();
var result = GetKCombs(new int[] {1,2,3,4,5}, 3);
foreach (var item in result)
{
    string s = string.Join(",", item);
    vectors.Add(s);
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900