Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Something like the following should do the job, I think.</p> <pre><code>public static IEnumerable&lt;IEnumerable&lt;int&gt;&gt; AllSequences(int start, int end, int size) { return size &lt;= 0 ? new[] { new int[0] } : from i in Enumerable.Range(start, end - size - start + 2) from seq in AllSequences(i + 1, end, size - 1) select Enumerable.Concat(new[] { i }, seq); } </code></pre> <p>The key to the solution is the <a href="http://msdn.microsoft.com/en-us/library/bb383978.aspx" rel="noreferrer">compound <code>from</code> clause</a>, which is quite handy for dealing with nested enumerables.</p> <p>Notice that I've changed the method signature slightly to <code>IEnumerable&lt;IEnumerable&lt;int&gt;&gt;</code>, since this is more convenient when using (pure) LINQ. You can always convert it easily to a <code>IEnumerable&lt;ICollection&lt;int&gt;&gt;</code> at the end if you like, however.</p> <p>Let me know if the code needs any explanation, but I'm hoping the LINQ syntax makes it reasonably clear.</p> <p><strong>Edit 1:</strong> Fixed bug and improved conciseness.</p> <p><strong>Edit 2:</strong> Because I'm bored and have nothing better to do (no, not really), I thought I'd write an extension method that compute the combinations of a given list of elements, making use of the <code>AllSequences</code> method.</p> <pre><code>public static IEnumerable&lt;IEnumerable&lt;T&gt;&gt; Combinations&lt;T&gt;(this IList&lt;T&gt; source, int num) { return AllSequences(0, source.Count - 1, num).Select( seq =&gt; seq.Select(i =&gt; source[i])); } </code></pre> <p>Perhaps not the most efficient way of computing combinations, but certainly pretty compact code!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload