【问题标题】:Reflection in C#: Grouping properties and calculate sum of another propertiesC# 中的反射:对属性进行分组并计算其他属性的总和
【发布时间】:2020-06-16 12:19:12
【问题描述】:

所以,我有这样的课:

 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(),它将使用泛型类和反射,并返回按 PaymentType 分组的 Dictionary,以及每个 PaymentType 的总和。 所以结果应该是:

[{"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;
        }
    }

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

【问题讨论】:

  • 这有点含糊。不要指望人们会编写您的代码,人们很乐意帮助您编写现有代码。你试过什么?向我们展示您的实施。如果您还没有,这里有一些初学者:GetPropertiesGetCustomAttributes。总而言之,this
  • 我不明白如果你已经有一个列表,你为什么要使用反射?只是将您的第一项列表和金额分组?
  • @Frenchy 抱歉,我有一个 TModel 列表,会更新描述
  • 好的,你是如何建立你的名单的?你能显示代码吗
  • @dowhilefor 感谢有用的链接!我可以使用 typeof(TPaymentsModel).GetProperties 找到必要属性的名称,并且可以使用 GetValue() 找到列表中每个对象的值。但是如何按一个特定属性对通用列表中的值进行分组,并对另一个属性的值求和

标签: c# reflection


【解决方案1】:

您可以采用的可能解决方案:

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

【讨论】:

    猜你喜欢
    • 2020-02-05
    • 2020-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2016-03-03
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多