I have a list of strings that I want to 'stack', for example if there are 2 lines in the array of strings that are "Egg" then it would display as "Egg x2" in a single string. I'm trying to achieve this by putting a for loop inside a for loop. For some reason the code below is sometimes returning more than 1 debug message, meaning it is being ran more than once(!?). Code (CSharp): Debug.Log("Stacking Ingredients..."); string path = Application.dataPath + "/Resources/ShoppingList.txt"; string data = System.IO.File.ReadAllText(path); lines = data.Split("\n"[0]); for (int i = 0; i < lines.Length - 1; i++) //A { for (int x = 0; x < lines.Length - 1; x++) //B (1) { string a = lines[i]; string b = lines[x]; Debug.Log(i + " and " + x); Debug.Log("Checking if A (" + a + ") is equal to B (" + b + ")"); if (a == b) { //Result } } } I'm clueless as to why the first Debug.Log is being returned once, and the next one is being returned 12 times, any pointers would be great.
That will be because the line is unique. The for loops will iterate over each number once. Therefore the permutation of 2 and 0 will only occur once (as will the permutation 0 and 2 which is different). Presumably Curry Jar appears once in your list and Chickpeas appears 12 times?
Try disabling "Collapse" in the console. The first message might only have the number one, as i or x have changed and therefor the message is different and not stacked with the other messages. Yeah, what @Doug_B said
An alternative approach would be to use a Dictionary. Something like this: Code (CSharp): var lines = data.Split('\n'); Dictionary<string, int> inventory = new Dictionary<string, int>(); foreach (var item in lines) { if (!inventory.ContainsKey(item)) inventory[item] = 1; else inventory[item] += 1; }