Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

How to get all possible combinations from a list of numbers in C#

1 Answer

0 votes
using System;
using System.Linq;
using System.Collections.Generic;

class Program
{
    public static IEnumerable<IEnumerable<T>> Combinations<T>(List<T> list) {
        return from n in Enumerable.Range(0, 1 << list.Count)
                select
                from i in Enumerable.Range(0, list.Count)
                where (n & (1 << i)) != 0
                select list[i];
    }


    static void Main() {
        var list = new List<int> { 3, 6, 0, 8 };
    
        var result = Combinations(list);

        Console.Write(string.Join("\n", result.Select(subset => 
                      string.Join(", ", subset.Select(r => r.ToString())))));
    }
}



/*
run:


3
6
3, 6
0
3, 0
6, 0
3, 6, 0
8
3, 8
6, 8
3, 6, 8
0, 8
3, 0, 8
6, 0, 8
3, 6, 0, 8

*/

 



answered Oct 15, 2022 by avibootz
...