I have date going in to a text file, form the variable nameSplit. The following code is checking to see if the string that has come from the text file to nameSplit had previously been saved to the dictionary. If so, then it prints "Hoozah!", else it adds the data to the array and prints "Failure". However, if I enter the name "Jim" 5 times in to the text file, it just outputs `Failure", although it should have outputted "hoozah!" on the second entry. I'm not sure what is wrong!
while (!sR.EndOfStream) { string line = sR.ReadLine(); string split = line.Split('$', ',')[1]; string nameSplit = line.Split('.', ':')[1]; Dictionary<string, decimal> names = new Dictionary<string, decimal>(); // inside the loop decimal n = Convert.ToDecimal(split); if (names.ContainsKey(nameSplit)) { names[nameSplit] += n; names.Add(nameSplit, n); Console.WriteLine("Hoozah!"); } else { names.Add(nameSplit, n); Console.WriteLine("Failure"); } } sR.Close(); GC.Collect(); Thread.Sleep(66); DATA:
- Jim: $22.00, 2. Jim: $2100.00, 3. Jim: $6.00, 4. Jim: $32.00, 5. Jim: $2.00,
GC.Collect()there at the end. You almost never need to deal directly with the garbage collector.