c# - C# 中的反射:对属性进行分组并计算其他属性的总和
问题描述
所以,我有这样的课:
public class PaymentsModel
{
[ReportsSummary(isGroupingSource:true)]
public string PaymentType { get; set; }
[ReportsSummary(isGroupingTarget: true)]
public double Amount { get; set; }
public string GuestName { get; set; }
}
我有(通用)列表,其中包含具有不同值的不同对象,例如:
{"Bank", 1, "K"},
{"Card", 2, "C"},
{"Cash", 3, "D"},
{"Bank", 2, "E"},
{"Card", 3, "G"},
我需要一个方法 CalculateSum(),它将使用泛型类和反射,并返回 Dictionary 并按 PaymentType 分组,并为每个 PaymentType 求和 Amount。所以结果应该是:
[{"Bank", 3},
{"Card", 5},
{"Cash", 5}]
我创建了一个属性来理解,应该对哪个属性进行分组,以及哪个属性 - 总和:
class ReportsSummaryAttribute : Attribute
{
public bool IsGroupingSource { get; private set; }
public bool IsGroupingTarget { get; private set; }
public ReportsSummaryAttribute(bool isGroupingSource = false, bool isGroupingTarget = false)
{
IsGroupingSource = isGroupingSource;
IsGroupingTarget = isGroupingTarget;
}
}
但是不明白,如何创建正确的方法。
解决方案
您可以适应的可能解决方案:
public class MyGenericClass<T> where T:PaymentsModel//or common baseType
{
public Dictionary<string, double> genericMethod(List<T> source)
{
var result = source.GroupBy(x => x.PaymentType)
.Select(t => new { PaymentType = t.Key, Total = t.Sum(u => u.Amount) })
.ToDictionary(t => t.PaymentType, t => t.Total);
return result;
}
}
:
:
//in processus
var myGenericClass = new MyGenericClass<PaymentsModel>();
var result = myGenericClass.genericMethod(source);
推荐阅读
- java - 如何修复测试依赖项中的拆分包?
- java - 使用 openjfx 插件时,Gradle 不会在 Mac 上的 Eclipse 中构建 Java 路径
- azure-devops - 在 Azure Devops 中创建角色用户后将 AzureAD 链接到组织域的影响
- javascript - 在酶中模拟焦点不会改变 document.activeElement
- javascript - 如何实现计数缺失括号?
- node.js - 使用nodejs将数据库(sql server)中的数据保存到全局变量中
- java - 仅当模型存在时才更新 JPA
- awk - 提取第二对引号之间的值
- python - 用于查看今天是否创建文件的 Python 脚本,发送带有结果的电子邮件
- haskell - 有没有办法在 Haskell 中按索引提取字符串?