Note that there are some explanatory texts on larger screens.

plurals
  1. POC# algorithm refactor splitting an array into 3 parts?
    primarykey
    data
    text
    <p>I have an IEnumerable and I wanted to split the data across 3 columns using the following business logic. if 3 or less items, 1 item per column, anything else I wanted to divide the total items by 3 split the leftovers (either 1 or 2 items) between the first two columns. Now this is pretty ugly but it does the job. I'm looking for tips to leverage linq a little better or possibly eliminate the switch statement. Any advice or tips that improve the code are appreciated.</p> <pre><code>var numItems = items.Count; IEnumerable&lt;JToken&gt; col1Items, col2Items, col3Items; if(numItems &lt;=3) { col1Items = items.Take(1); col2Items = items.Skip(1).Take(1); col3Items = items.Skip(2).Take(1); } else { int remainder = numItems % 3, take = numItems / 3, col1Take, col2Take, col3Take; switch(remainder) { case 1: col1Take = take + 1; col2Take = take; col3Take = take; break; case 2: col1Take = take + 1; col2Take = take + 1; col3Take = take; break; default: col1Take = take; col2Take = take; col3Take = take; break; } col1Items = items.Take(col1Take); col2Items = items.Skip(col1Take).Take(col2Take); col3Items = items.Skip(col1Take + col2Take).Take(col3Take); </code></pre> <p>Ultimately I am using these in a mvc Razor view</p> <pre><code>&lt;div class="widgetColumn"&gt; @Html.DisplayFor(m =&gt; col1Items, "MenuColumn") &lt;/div&gt; &lt;div class="widgetColumn"&gt; @Html.DisplayFor(m =&gt; col2Items, "MenuColumn") &lt;/div&gt; &lt;div class="widgetColumn"&gt; @Html.DisplayFor(m =&gt; col3Items, "MenuColumn") &lt;/div&gt; </code></pre> <p>In my first attempt I want to get rid of the colNItems and colNTake variables but i can't figure out the correct algorithm to make it work the same.</p> <pre><code>for (int i = 1; i &lt;= 3; i++ ) { IEnumerable&lt;JToken&gt; widgets = new List&lt;JToken&gt;(); var col = i; switch(col) { case 1: break; case 2: break; case 3: break; } } </code></pre>
    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.
 

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