2

I have the following code:

var ccdata = dict1.Select(i => 
                          new object[] { i.Key, Int32.Parse(i.Value) }
                         ).ToArray();

I need to get the sum of all of the i.Value's. Please note this is a multidimensional object array. i.Key is a string value and i.Value is a int value which needs to be summed up.

Thank you in advance

4
  • 2
    Why are you putting the two into an object array, thereby boxing everything? Commented Oct 18, 2011 at 19:37
  • What i.Value is string? Why do you parse it, why isn't it initially a number? Commented Oct 18, 2011 at 19:43
  • if I.Value is already an int then int.Parse will not compile since it expects a string. Is it a string or an int? Commented Oct 18, 2011 at 20:00
  • 1
    @JonSkeet: Because when he asked how to create a multidimensional array, I suggested doing it with Linq. Looks like he didn't bother looking up what Linq is all about and hoped random code he gets from this site can be combined into a working solution. Commented Oct 19, 2011 at 2:51

3 Answers 3

3
dic.Sum(i => Int32.Parse(i.Value)); // if i.Value is string instead of just int

dic.Sum(i => i.Value); // if string

or

ccdata.Sum(i => (int)i[1]); // if i[1] is object instead of just int

ccdata.Sum(i => i[1]); // if int
Sign up to request clarification or add additional context in comments.

1 Comment

The latter will fail to compile, as the compile-time type of i[1] is just object.
2

It's unclear why you're doing it in quite this way, but it's fairly easy to sum them...

int sum = ccdata.Sum(x => (int) x[1]);

It would be clearer and more efficient if you used:

var ccdata = dict1.Select(i => new { i.Key, Value = Int32.Parse(i.Value) })
                  .ToArray();

That way you end up with compile-time type safety and no boxing:

int sum = ccdata.Sum(x => x.Value);

(I'm assuming you actually want ccdata for some other reason. Otherwise, use abatishchev's solution and get rid of your existing code altogether.)

Comments

1

i.Value is at the second position in your inner array. So it should go like that:

var sum = cdata.Sum(arr => (int)arr[1]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.