0

I'm wondering if I can do the following query dynamically.

        var perms = from a in matrix[0]
                    from b in matrix[1]
                    from c in matrix[2]
                    select new[] { a, b, c};

matrix is a dynamic object and I'd like to have the same query working regardless of the matrix dimensions.

Thanks.

Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
Puhek
  • 475
  • 3
  • 13
  • 2
    I'm not exactly sure what you're asking, Puhek...do you mean that if `matrix` has two elements in it, you would only select `a` and `b`, but if it had three elements in it, you would select `a` through `d`, etc.? Or are there always three elements in `matrix`, but its members may have collections of varying dimensions? – Ethan Brown Apr 28 '12 at 20:36
  • sorry; Matrix is actually a [n][] object. So what I've got is n of arrays with each different size. What i'd like to achieve is to make a query that would dynamically do all the permutations on the inner arrays. The example does it for three inner arrays and I'd just like to have it done generally for whatever Matrix[][] size. – Puhek Apr 28 '12 at 20:59
  • 1
    It sounds like you're asking about [Generating all Possible Combinations](http://stackoverflow.com/questions/3093622/generating-all-possible-combinations) (or a Cartesian Product). – Gabe Apr 28 '12 at 21:16
  • 2
    See also: http://blogs.msdn.com/b/ericlippert/archive/2010/06/28/computing-a-cartesian-product-with-linq.aspx – Gabe Apr 28 '12 at 21:19

2 Answers2

1

You can accomplish this using an aggregator:

IEnumerable<IEnumerable<int>> l = new[] { Enumerable.Empty<int>() };
var perms = matrix.Aggregate( l, (accumulator, seq) =>
  from a in accumulator from s in seq select a.Concat( new[] { s } ) );
Ethan Brown
  • 26,892
  • 4
  • 80
  • 92
0

Is it necessary to declare matrix as dynamic? I think this code works as you want:

 var matrix = new int[3][] { new int[] { 1 }, new int[] { 2, 2 }, new int[] { 3, 3, 3 } };
 var perms = from a in matrix[0]
             from b in matrix[1]
             from c in matrix[2]
             select new[] { a, b, c };
tech-man
  • 3,166
  • 2
  • 17
  • 18
  • Sorry I have not been clear enough. It's not that object itself is dynamic, I wanted to say that I need a query that would "dynamically" extend from three "from" clauses to general number of those (and make a new array). – Puhek Apr 28 '12 at 21:02