如何使用linq函数,如Sum()与动态变量

本文关键字:动态 变量 Sum 何使用 linq 函数 | 更新日期: 2023-09-27 17:54:58

Type t = Type.GetType(obj.ToString());                 
PropertyInfo p = t.GetProperty("Test");
dynamic kk =  p.GetValue(obj, null);

在这里,Test是一个整型列表。我需要从int list中得到所有值的总和。kk。

如何使用linq函数,如Sum()与动态变量

var list = p.GetValue(obj, null) as IEnumerable<int>;
var result = list.Sum();
// Type t = Type.GetType(obj.ToString());
Type t = obj.GetType(); // You might be able to replace the above line with this, simpler verison.
PropertyInfo p = t.GetProperty("Test");
object kk =  p.GetValue(obj, null);
int Sum = (kk as List<int>).Sum();