mardi 16 juin 2020

Reflection in C#: Grouping properties and calculate sum of another properties

So, I have such class:

 public class PaymentsModel
    {
        [ReportsSummary(isGroupingSource:true)]
        public string PaymentType { get; set; }

        [ReportsSummary(isGroupingTarget: true)]
        public double Amount { get; set; }

        public string GuestName { get; set; }
}

I have List of (generic) which contains different objects with different values, for example:

{"Bank", 1, "K"},
{"Card", 2, "C"},
{"Cash", 3, "D"},
{"Bank", 2, "E"},
{"Card", 3, "G"},

I need a method CalculateSum() which will use generic class and reflection, and return Dictionary with grouping by PaymentType, and sum Amount for each PaymentType. So result should be:

[{"Bank", 3},
{"Card", 5},
{"Cash", 5}]

I created an attribute to understand, which property should be grouped, and which - summed:

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

But don't understand, how to create correct method.





Aucun commentaire:

Enregistrer un commentaire