Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This can be solved elegantly using Linq:</p> <pre><code>public static void Main(string[] args) { List&lt;int&gt; list = new List&lt;int&gt; { 2, 3, 4, 5, 2, 4, 6, 2, 4, 7, 3, 8, 2 }; var grouping = list .GroupBy(x =&gt; x) .Select(x =&gt; new { Item = x.Key, Count = x.Count()}); foreach (var item in grouping) Console.WriteLine("Item {0} has count {1}", item.Item, item.Count); } </code></pre> <p>Internally it probably uses hashing to partition the list, but the code hides the internal details - here we are only telling it <em>what</em> to calculate. The compiler / runtime is free to choose <em>how</em> to calculate it, and optimize as it sees fit. Thanks to Linq this same code will run efficiently whether run an a list in memory, or if the list is in a database. In real code you should use this, but I guess you want to know how internally it works.</p> <p>A more imperative approach that demonstrates the actual algorithm is as follows:</p> <pre><code> List&lt;int&gt; list = new List&lt;int&gt; { 2, 3, 4, 5, 2, 4, 6, 2, 4, 7, 3, 8, 2 }; Dictionary&lt;int, int&gt; counts = new Dictionary&lt;int, int&gt;(); foreach (int item in list) { if (!counts.ContainsKey(item)) { counts[item] = 1; } else { counts[item]++; } } foreach (KeyValuePair&lt;int, int&gt; item in counts) Console.WriteLine("Item {0} has count {1}", item.Key, item.Value); </code></pre> <p>Here you can see that we iterate over the list only once, keeping a count for each item we see on the way. This would be a bad idea if the items were in a database though, so for real code, prefer to use the Linq method.</p>
 

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