Use LINQ GroupBy to count occurrences
LINQ provides a convenient way to group data items based on specified keys and count their occurrences. Consider the following dataset:
<code>UserInfo(name, metric, day, other_metric)</code>
Sample data:
<code>joe 1 01/01/2011 5 jane 0 01/02/2011 9 john 2 01/03/2011 0 jim 3 01/04/2011 1 jean 1 01/05/2011 3 jill 2 01/06/2011 5 jeb 0 01/07/2011 3 jenn 0 01/08/2011 7</code>
The goal is to create a table that lists the metrics in order and their total number of occurrences. The appropriate LINQ expression is as follows:
<code>var counts = data.GroupBy(i => i.metric) .Select(g => new { Metric = g.Key, Count = g.Count() }) .OrderBy(r => r.Metric);</code>
It works as follows:
metric
based on the data
attribute. This will produce a collection of groups, each group representing a unique metric value. Executing this LINQ expression will produce the desired output:
<code>0 3 1 2 2 2 3 1</code>
The above is the detailed content of How Can LINQ GroupBy Be Used to Count Metric Occurrences in a Dataset?. For more information, please follow other related articles on the PHP Chinese website!