Note that there are some explanatory texts on larger screens.

plurals
  1. POin C#, how do I order items in a list where the "largest" values are in the middle of the list
    text
    copied!<p>I have been stumped on this one for a while. I want to take a List and order the list such that the Products with the largest Price end up in the middle of the list. And I also want to do the opposite, i.e. make sure that the items with the largest price end up on the outer boundaries of the list.</p> <p>Imagine a data structure like this.. 1,2,3,4,5,6,7,8,9,10</p> <p>In the first scenario I need to get back 1,3,5,7,9,10,8,6,4,2 In the second scenario I need to get back 10,8,6,4,2,1,3,5,7,9</p> <p>The list may have upwards of 250 items, the numbers will not be evenly distributed, and they will not be sequential, and I wanted to minimize copying. The numbers will be contained in Product objects, and not simple primitive integers.</p> <p>Is there a simple solution that I am not seeing?</p> <p>Any thoughts.</p> <p>So for those of you wondering what I am up to, I am ordering items based on calculated font size. Here is the code that I went with...</p> <p>The Implementation...</p> <pre><code>private void Reorder() { var tempList = new LinkedList&lt;DisplayTag&gt;(); bool even = true; foreach (var tag in this) { if (even) tempList.AddLast(tag); else tempList.AddFirst(tag); even = !even; } this.Clear(); this.AddRange(tempList); } </code></pre> <p>The Test...</p> <pre><code>[TestCase(DisplayTagOrder.SmallestToLargest, Result=new[]{10,14,18,22,26,30})] [TestCase(DisplayTagOrder.LargestToSmallest, Result=new[]{30,26,22,18,14,10})] [TestCase(DisplayTagOrder.LargestInTheMiddle, Result = new[] { 10, 18, 26, 30, 22, 14 })] [TestCase(DisplayTagOrder.LargestOnTheEnds, Result = new[] { 30, 22, 14, 10, 18, 26 })] public int[] CalculateFontSize_Orders_Tags_Appropriately(DisplayTagOrder sortOrder) { list.CloudOrder = sortOrder; list.CalculateFontSize(); var result = (from displayTag in list select displayTag.FontSize).ToArray(); return result; } </code></pre> <p>The Usage...</p> <pre><code>public void CalculateFontSize() { GetMaximumRange(); GetMinimunRange(); CalculateDelta(); this.ForEach((displayTag) =&gt; CalculateFontSize(displayTag)); OrderByFontSize(); } private void OrderByFontSize() { switch (CloudOrder) { case DisplayTagOrder.SmallestToLargest: this.Sort((arg1, arg2) =&gt; arg1.FontSize.CompareTo(arg2.FontSize)); break; case DisplayTagOrder.LargestToSmallest: this.Sort(new LargestFirstComparer()); break; case DisplayTagOrder.LargestInTheMiddle: this.Sort(new LargestFirstComparer()); Reorder(); break; case DisplayTagOrder.LargestOnTheEnds: this.Sort(); Reorder(); break; } } </code></pre>
 

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