如何在 C# LINQ 中使用 3 个不同的 "qualities" IEnumerable.GroupBy<T> 进行计数?

How to IEnumerable.GroupBy<T> with 3 different "qualities" getting count in C# LINQ?

我想按从抽象 class 继承的对象列表分组:

  1. 列表中项目的类型(在此示例中为 MyAction 或 MyObservation)
  2. 一个整数属性ClassId
  3. 字符串属性值

并计算出这些组。

public abstract class MyData
{
    public int ClassId;
    public string Value;
    //...
}

public class MyAction : MyData
{
    //...
}

public class MyObservation : MyData
{
    //...
}

// in some class...
IEnumerable<MyData> _myDatas;

void TryGroupBy()
{
    var result = _myDatas.GroupBy(
               data => KeySelector(data), /* ?? key is 3 pieces of info */,
               data => ElementSelector/* ?? I didn't get this either */,
               (row, rows) => new 
               {
                   ClassId = ?? /*how to get it from 3 piece key */
                   TypeOfObject = /* how to get it ?? */
                   Value = /* how to get it ?? */
                   Count = rows.Count
               }));

您可以使用匿名类型作为键,然后使用 Key 属性(例如 group.Key.Id)访问属性,或者您可以使用 this overload您将键作为结果选择器的第一个参数:

_myDatas.GroupBy(
           data => new { Type = data.GetType(), Id = data.ClassId, Value = data.Value },
           (key, rows) => new 
           {
               ClassId = key.Id,
               TypeOfObject = key.Type,
               Value = key.Value,
               Count = rows.Count()
           }));