Generate number sequences with LINQ

Posted by tanascius on Stack Overflow See other posts from Stack Overflow or by tanascius
Published on 2010-04-29T12:04:39Z Indexed on 2010/04/29 12:07 UTC
Read the original article Hit count: 377

Filed under:
|

I try to write a LINQ statement which returns me all possible combinations of numbers (I need this for a test and I was inspired by this article of Eric Lippert). The method's prototype I call looks like:

IEnumerable<Collection<int>> AllSequences( int start, int end, int size );

The rules are:

  • all returned collections have a length of size
  • number values within a collection have to increase
  • every number between start and end should be used

So calling the AllSequences( 1, 5, 3 ) should result in 10 collections, each of size 3:

1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4 
2 3 5
2 4 5 
3 4 5

Now, somehow I'd really like to see a pure LINQ solution. I am able to write a non LINQ solution on my own, so please put no effort into a solution without LINQ.
My tries so far ended at a point where I have to join a number with the result of a recursive call of my method - something like:

return from i in Enumerable.Range( start, end - size + 1 )
       select BuildCollection(i, AllSequences( i, end, size -1));

But I can't manage it to implement BuildCollection() on a LINQ base - or even skip this method call. Can you help me here?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ