4

I was collect data an array with 2 coloumn look like this

---------------
Order  | Value
---------------
order1 | 45
order2 | 70
order1 | 85
order2 | 32
--------------

How to get all value in the array based conditional where order= order1 only and sum them?

Thank you,

3
  • I'd use LINQ. Have you looked at that at all yet? If so, show what you've tried and what went wrong. (Hint: you should be able to do it with a call to Where and a call to Sum.) It's not really clear why you're using a 2D array rather than a type which encapsulates the order name and value, mind you. It's also not clear whether this is a rectangular array or a jagged array. A minimal reproducible example would make it easier to help you. Commented Jul 27, 2016 at 6:38
  • @JonSkeet I don't think he meant a 2-D array (the one we know it) because I don't think a 2-D array can hold a string in one dimension and a number in the second. Unless it is an object array (which is unlikely) Commented Jul 27, 2016 at 6:43
  • @user3185569: It's hard to tell for sure, to be honest. That's why I asked for a minimal reproducible example. Commented Jul 27, 2016 at 6:57

1 Answer 1

5

Using Linq (Where for Conditional) and (Sum for Aggregate Functions):

var sum = array.Where(x=> x.Order == "order1").Sum(x=> x.Value);

If you really meant a 2-D (Multidimentional) Array, then you can do this:

object[,] array = 
{
    { "order1", 45 }, { "order2", 70 },
    { "order1", 85 }, { "order2", 32 }
};


decimal Sum = 0;
for(int i = 0; i < array.GetLength(0); i++)
{
    if (array.GetValue(i, 0)?.ToString() == "order1")
    {
        decimal val;
        if(decimal.TryParse(array.GetValue(i, 1)?.ToString(), out val))
            Sum += val;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Can you please give me a complete code. I just started with simple array from this : string[,] ord = new string[7, 3]; How to implement that linq code with that array? Thank you
Thank you very much. But if you deign, how if I not use 2D array, like this array : string[,] ord = new string[7, 3]; Please check the edited post. So how to started use linq if using that array?
@MFBM you can't use linq to get each row. You can use linq to get each element separately. Like order1, 45, order2, 70.
Thank you very much. But I still dificult to understand how to write in VB.NET code. I have try to manipulation your solution and convert into VB.Net code but is nothing. So can you help me, how if that solution writen with VB code If you have VB language? Btw Thanks you in advance
Hi Sehnsucht, Thank you for your help!

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.