首页 > 解决方案 > 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;
        }
    }

但是不明白,如何创建正确的方法。

标签: c#reflection

解决方案


您可以适应的可能解决方案:

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);

推荐阅读