GroupBy所有领域并得到统计

时间:2017-04-17 16:57:15

标签: c# linq

我有以下Customer课程:

public class Customer
{
    public string Name  {get; set;}
    public string Email {get; set;}
    public string City  {get; set;}
}

客户收藏

List<Customer> customers = //assigned range of customers

现在我需要按所有字段进行分组。我不想选择单个字段。在我的实际场景中,它运行更加动态,因此我无法预定义字段。

从这个customers对象我需要构建一个像

这样的矩阵
Name |   Email    | City | count
AB     ef@g.com     ss      3
CB      f@g.com     ss      2
EF      k@s.com     ss      34
ek      g.com       we      84

我试过这条路。 按多列分组的扩展方法

public static IEnumerable<GroupResult> GroupByMany<TElement>(
    this IEnumerable<TElement> elements, List<string> groupSelectors)
{
    var selectors =
        new List<Func<TElement, object>>(groupSelectors.Count);
    foreach (var selector in groupSelectors)
    {
        LambdaExpression lambdaExpression =
            System.Linq.Dynamic.DynamicExpression.ParseLambda(typeof(TElement), typeof(object), $"it[\"{selector}\"]");
        selectors.Add((Func<TElement, object>) lambdaExpression.Compile());
    }
    return elements.GroupByMany(selectors.ToArray());
}

并将其称为

customers.GroupByMany(displayFields);

问题是我将结果作为嵌套组

public class GroupResult
{
    public object Key { get; set; }
    public int Count { get; set; }
    public IEnumerable Items { get; set; }
    public IEnumerable<GroupResult> SubGroups { get; set; }
    public override string ToString()
    {
        return $"{Key} ({Count})";
    }
}

这远远超出我的需要。

1 个答案:

答案 0 :(得分:1)

要按整个对象进行分组并计算出现次数(或者换句话说“计算重复数”),只需按迭代项进行分组,如下所示:

var result = from item in customers
             group 1 by item into grouping
             select new {
                 grouping.Key,
                 Count = grouping.Count()
             };

样本数据:

var customers = new List<Customer>
{
    new Customer { Name = "a", City = "a" },
    new Customer { Name = "a", City = "a" },
    new Customer { Name = "a", City = "b" },
    new Customer { Name = "b", City = "b" }
};

结果是:

enter image description here

请注意,Customer对象的分组使用其EqualsGetHashCode来比较对象,然后确保覆盖它们。您可以查看this question

另请参阅对象的所有属性都是Key中的属性,这些属性与您的示例输出不对齐,但与您显示的GroupResult对齐