I have a list of integers in my C# program. However, I know the number of items I have in my list only at runtime.
Let us say, for the sake of simplicity, my list is {1, 2, 3} Now I need to generate all possible combinations as follows. {1, 2, 3} {1, 2} {1, 3} {2, 3} {1} {2} {3}
Can somebody please help with this?
Here's a generic solution using recursion
I know this is an old post, but someone might find this helpful.
A slightly more generalised version for Linq using C# 7. Here filtering by items that have two elements.
What about
Here are two generic solutions for strongly typed lists that will return all unique combinations of list members (if you can solve this with simpler code, I salute you):
Firstly, given a set of n elements, you compute all combinations of k elements out of it (nCk). You have to change the value of k from 1 to n to meet your requirement.
See this codeproject article for C# code for generating combinations.
In case, you are interested in developing the combination algorithm by yourself, check this SO question where there are a lot of links to the relevant material.
try this: