开发者

Compute the sum of a sequence of object values inside a System.Array instance

开发者 https://www.devze.com 2023-04-01 13:04 出处:网络
I have this code: private object Add(object a, object b) { // Assume: a a开发者_如何学编程nd b are the same types.

I have this code:

private object Add(object a, object b)
{
    // Assume: a a开发者_如何学编程nd b are the same types.
    // Assume: a and b are numeric types (ex. int).

    Array array = Array.CreateInstance(a.GetType(), 2);
    array.SetValue(a, 0);
    array.SetValue(b, 1);

    // Is it possible to return the Sum of the values inside the Array instance?
}

There are many alternative (and of course better) ways to do this using a regular array, generics or avoid passing object and just pass int, double, etc.

Just trying to figure out if this is possible at all (without the use of dynamic primitive type).


If you know that the array contains only ints, you can do that:

int sum = array.Cast<int>().Sum();

If the array contains integer numeric values, but you don't know their type, you can try something like that:

long sum = array.Cast<object>().Select(o => Convert.ToInt64(o)).Sum();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号