gpt4 book ai didi

c# - 通过匿名传递列名对通用列表的一列求和

转载 作者:太空宇宙 更新时间:2023-11-03 21:28:18 24 4
gpt4 key购买 nike

我的代码是这样的

 private static void ShowSum(Label lbl, IEnumerable<dynamic> list, string columnName)
{
lbl.Text = list.Sum(x => x.columnName).ToString();
}

每次调用此函数时,我都试图获取特定列的总和,列名将作为参数传递给此函数。截至目前,这不起作用,因为 columnName 被解释为特定列名称的字符串。实现这一目标的正确方法是什么?

最佳答案

您需要使用反射来通过名称从动态对象中获取属性:

lbl.Text = list.Sum(x => x.GetType().GetProperty(columnName).GetValue(x, null)).ToString();

但我建议您使用强类型而不是动态类型。至少您将能够在编译时而不是运行时捕获一些错误。

关于c# - 通过匿名传递列名对通用列表的一列求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25645361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com