Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose One Element From Each Set Without Ordering

Tags:

c#

Please consider the following code:

List<string> a = new List<string>(new string[] { "a1", "a2" });
List<string> b = new List<string>(new string[] { "b1", "b2" });
List<string> c = new List<string>(new string[] { "c1", "c2" });
List<List<string>> input = new List<List<string>>();
input.Add(a);
input.Add(b);
input.Add(c);
List<List<string>> output=List<List<string>> PickOneFromEachSet(input)

PickOneFromEachSet would pick an element from each set without considering the ordering.

We can have 2^3=8 combinations, i.e. the output would be

{"a1","b1","c1"},
{"a1","b1","c2"},
...
{"a2","b2","c2"}

How should we construct such a function?

like image 315
william007 Avatar asked Feb 03 '26 12:02

william007


1 Answers

If there will always be three sets, it's easy:

var query = from aValue in a
            from bValue in b
            from cValue in c
            select new List<string> { aValue, bValue, cValue };
List<List<string>> output = query.ToList();
like image 51
Jon Skeet Avatar answered Feb 05 '26 02:02

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!