LINQ with groupby and count

前端 未结 3 1257
情话喂你
情话喂你 2020-11-22 17:32

This is pretty simple but I\'m at a loss: Given this type of data set:

UserInfo(name, metric, day, other_metric)

and this sample data set:

3条回答
  •  北海茫月
    2020-11-22 18:03

    Assuming userInfoList is a List:

            var groups = userInfoList
                .GroupBy(n => n.metric)
                .Select(n => new
                {
                    MetricName = n.Key,
                    MetricCount = n.Count()
                }
                )
                .OrderBy(n => n.MetricName);
    

    The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

    Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

提交回复
热议问题