如何使用Sumq函数(如Sum()和动态变量)

时间:2011-05-06 06:35:45

标签: c# linq dynamic

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

在此,Test是一个int List。我需要得到int list中所有值的总和,即。,kk。

2 个答案:

答案 0 :(得分:6)

var list = p.GetValue(obj, null) as IEnumerable<int>;

var result = list.Sum();

答案 1 :(得分:0)

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