Looping through array

Jedidia
Jedidia used Ask the Experts™
on
Can someone help me with the logic of looping through an array.
I would like to identifying like strings in a specific location [i,2] and add the associated values in [i,3] and save the results into a new array or list.

Graphically trying to do this.

Example
Thanks for any assistance.

Regards,
Jed-
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Fernando SotoRetired
Distinguished Expert 2017

Commented:
Hi Jedidia;

In your example how do you differentiate between the AAA's at the top of the array and the AAA's at the bottom of the array because the List at the right has two AAA's group?

Author

Commented:
You can't differentiate them other than their location in the array.
The only way I can think of doing this is to grab the first row in the array and test this value against the next in a loop?
NorieAnalyst Assistant

Commented:
Jed

How are you currently storing the first array?
PMI ACP® Project Management

Prepare for the PMI Agile Certified Practitioner (PMI-ACP)® exam, which formally recognizes your knowledge of agile principles and your skill with agile techniques.

Author

Commented:
Sorting the array as follows
string[,] updatedData = new string[((lineCount) / 2), 38];

There is alot of other data that is not important to the new list/array.
If I'm understanding what you're trying to do correctly, I would use the constructs in the .NET Framework that make this type of thing easier. Specifically, I would use a Dictionary<string, double> to make the summing by label much easier to code and understand exactly what is happening. Going this route makes things trivially simple:

var result = new Dictionary<string, double>();

for (var i = 0; i < data.Length / 2; i++)
{
	double value;
	var key = data[i, 0];
	double.TryParse(data[i, 1], out value);

	if (result.ContainsKey(key))
	{
		result[key] += value;
	}
	else
	{
		result.Add(key, value);
	}
}

Open in new window

Here's a working fiddle where you can see it in action and make real-time adjustments to suit your needs.
Top Expert 2014

Commented:
Using a Dictionary won't work because the same key can appear several times.
Here is a method that groups the labels by proximity.
        static IEnumerable<(string, double)> Sum(this string[,] array)
        {
            string key = null;
            double sum = 0;
            int i;
            for (i = 0; i < array.GetLength(0); i++)
            {
                if (i != 0 && key != array[i, 0])
                    yield return (key, sum);

                double.TryParse(array[i, 1], out var value);
                if (key == array[i, 0])
                {
                    sum += value;
                }
                else
                {
                    key = array[i, 0];
                    sum = 0;
                }
            }
            if (i != 0)
                yield return (key, sum);
        }

Open in new window

@louisfr In this case the dictionary will absolutely work. The key check in line 9 below prevents it from being duplicated.
Did you actually look at the working  dotnetfiddle that was provided in the answer?

var result = new Dictionary<string, double>();

for (var i = 0; i < data.Length / 2; i++)
{
	double value;
	var key = data[i, 0];
	double.TryParse(data[i, 1], out value);

	if (result.ContainsKey(key))
	{
		result[key] += value;
	}
	else
	{
		result.Add(key, value);
	}
}

Open in new window

Top Expert 2014

Commented:
I didn't need to test it to know it doesn't get the expected result.
Since a dictionary can't have the same key twice, you're adding the 3 first lines from the example with the 3 last lines.
Your result:
AAA: 259.5
BBB : 8913.4
CCC: 26

Open in new window

Expected result:
AAA: 38.5
BBB : 8913.4
CCC: 26
AAA: 221

Open in new window

@Jed, is there a difference between the top 'AAA' and the bottom 'AAA', or are they the same label?

Author

Commented:
@Kelvin, Yes, your solution combines all the like values into one record like the below.

AAA: 259.5
BBB : 8913.4
CCC: 26

I have not been able to get @louisfr's suggestion to work (but will try again later tonight or tomorrow morning).
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
If you install morelinq from NuGet into your project, then you can use the GroupAdjacent function:

using MoreLinq;
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp14
{
    class Program
    {
        static void Main(string[] args)
        {
            var array = new List<KeyValuePair<string, double>>()
                        {
                            new KeyValuePair<string, double>("AAA", 1.8),
                            new KeyValuePair<string, double>("AAA", 25.7),
                            new KeyValuePair<string, double>("AAA", 11),
                            new KeyValuePair<string, double>("BBB", .4),
                            new KeyValuePair<string, double>("BBB", 44),
                            new KeyValuePair<string, double>("BBB", 8846),
                            new KeyValuePair<string, double>("BBB", 23),
                            new KeyValuePair<string, double>("CCC", 15),
                            new KeyValuePair<string, double>("CCC", 11),
                            new KeyValuePair<string, double>("AAA", 135),
                            new KeyValuePair<string, double>("AAA", 31),
                            new KeyValuePair<string, double>("AAA", 55),
                        };

            var grouped = array.GroupAdjacent(item => item.Key);

            foreach (var group in grouped)
            {
                Console.WriteLine("{0} => {1}", group.Key, group.Sum(item => item.Value));
            }

            Console.ReadKey();
        }
    }
}

Open in new window


Screenshot

Author

Commented:
Thank you all.

I was able to get my code working based off the kaufmed example.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial