jagan
jagan

Reputation: 21

How to use linq functions like Sum() with dynamic variable

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

In this, Test is an int List. I need to get the sum of all the values from int list ie., kk.

Upvotes: 2

Views: 2160

Answers (2)

George Duckett
George Duckett

Reputation: 32428

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

Upvotes: 0

Steven
Steven

Reputation: 172616

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

var result = list.Sum();

Upvotes: 6

Related Questions