title: Grouping data between ranges using LINQ in C#
body: <p>I have made a following code to create me a range between two numbers, and data is separated in 7 columns: </p>
  
  <pre><code>  private List&lt;double&gt; GetRangeForElements(double minPrice, double maxPrice)
          {
              double determineRange = Math.Round(maxPrice / 7.00d, 3);
              var ranges = new List&lt;double&gt;();
              ranges.Insert(0, Math.Round(minPrice, 3));
              ranges.Insert(1, determineRange);
              for (int i = 2; i &lt; 8; i++)
              {
                  ranges.Insert(i, Math.Round(determineRange * i, 3));
              }
              return ranges;
          }
  </code></pre>
  
  <p>Now I have list of ranges when I call the method:</p>
  
  <pre><code>var ranges = GetRangeForElements(1,1500);
  </code></pre>
  
  <p>On the other side now I have the data (a list) that contains following data (properties):</p>
  
  <pre><code>public double TransactionPrice {get;set;}
  
  public int SaleAmount {get;set;}
  </code></pre>
  
  <p>Input data would be:</p>
  
  <pre><code>Transaction price    Sale amount
  
  114.5                   4
  331.5                   6
  169.59                  8
  695.99                  14
  1222.56                 5
  </code></pre>
  
  <p>Generated range for between 1 and 1500 is:</p>
  
  <pre><code>1
  214.28
  428.57
  642.85
  857.14
  1071.43
  1285.71
  1500.00
  </code></pre>
  
  <p>And the desired output would be:</p>
  
  <pre><code>Range                    Sales
  (1 - 214.28)             12
  (214.28 - 428.57)        6
  (428.57 - 642.85)        0
  (642.85 - 857.14)        14
  (857.14 - 1071.43)       0 
  (1071.43 - 1285.71)      5    
  (1285.71 - 1500)         0
  </code></pre>
  
  <p>I've tried something like this:</p>
  
  <pre><code>var priceGroups = _groupedItems.GroupBy(x =&gt; ranges.FirstOrDefault(r =&gt; r &gt; x.TransactionPrice))
     .Select(g =&gt; new { Price = g.Key, Sales = g.Sum(x=&gt;x.Sales) })
     .ToList();
  </code></pre>
  
  <p>But this doesn't gives me what I want, the results I receive are completely messed up (I was able to verify the data and results manually)...</p>
  
  <p>Can someone help me out?</p>
  
  <p>P.S. guys, the ranges that have no sales should simply have value set to 0...</p>
  
  <p>@blinkenknight here's a pic of what I'm saying, min price is = 2.45 , max price = 2.45 </p>
  
  <p>and the output of the 2nd method you posted is:</p>
  
  <p><a href="https://i.stack.imgur.com/dOlRg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dOlRg.jpg" alt="enter image description here"></a></p>