I've a List of this type List> that contains this
List<int> A = new List<int> {1, 2, 3, 4, 5}; List<int> B = new List<int> {0, 1}; List<int> C = new List<int> {6}; List<int> X = new List<int> {....,....};
I want to have all combinations like this
1-0-6 1-1-6 2-0-6 2-1-6 3-0-6
and so on.
According to you is This possibile to resolve using Linq?
The unique combination of two lists in Python can be formed by pairing each element of the first list with the elements of the second list. Method 1 : Using permutation() of itertools package and zip() function. Approach : Import itertools package and initialize list_1 and list_2.
Once the queries from the tables are ready, go to Data > Get Data > Combine Queries > Merge to open the Merge dialog of Power Query. Select each table in the drop downs. Click on the column for each table to select them. Finally select Full Outer option for Join Kind to join by all rows from both tables.
It's quite similar to this answer I gave to another question:
var combinations = from a in A from b in B from c in C orderby a, b, c select new List<int> { a, b, c }; var x = combinations.ToList();
For a variable number of inputs, now with added generics:
var x = AllCombinationsOf(A, B, C); public static List<List<T>> AllCombinationsOf<T>(params List<T>[] sets) { // need array bounds checking etc for production var combinations = new List<List<T>>(); // prime the data foreach (var value in sets[0]) combinations.Add(new List<T> { value }); foreach (var set in sets.Skip(1)) combinations = AddExtraSet(combinations, set); return combinations; } private static List<List<T>> AddExtraSet<T> (List<List<T>> combinations, List<T> set) { var newCombinations = from value in set from combination in combinations select new List<T>(combination) { value }; return newCombinations.ToList(); }
If the number of dimensions is fixed, this is simply SelectMany
:
var qry = from a in A from b in B from c in C select new {A=a,B=b,C=c};
However, if the number of dimensions is controlled by the data, you need to use recursion:
static void Main() { List<List<int>> outerList = new List<List<int>> { new List<int>(){1, 2, 3, 4, 5}, new List<int>(){0, 1}, new List<int>(){6,3}, new List<int>(){1,3,5} }; int[] result = new int[outerList.Count]; Recurse(result, 0, outerList); } static void Recurse<TList>(int[] selected, int index, IEnumerable<TList> remaining) where TList : IEnumerable<int> { IEnumerable<int> nextList = remaining.FirstOrDefault(); if (nextList == null) { StringBuilder sb = new StringBuilder(); foreach (int i in selected) { sb.Append(i).Append(','); } if (sb.Length > 0) sb.Length--; Console.WriteLine(sb); } else { foreach (int i in nextList) { selected[index] = i; Recurse(selected, index + 1, remaining.Skip(1)); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With