我想按从抽象类继承的对象列表进行分组:
- 列表中项目的类型(在此示例中为 MyAction 或 MyObservation)
- 整数属性 ClassId
- 字符串属性值
并计算出这些组的数量。
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()
}));
关于c# - 如何使用 IEnumerable.GroupBy<T> 和 3 个不同的 "qualities"在 C# LINQ 中获取计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28767812/