C# IDictionary<char, int> -- How to increase value of int? | SoloLearn: Learn to code for FREE!

+2

C# IDictionary<char, int> -- How to increase value of int?

I am trying to up the value of the int in the key-value pair in a dictionary using the name[key] syntax. What is passed into the function is a string of various sizes. I iterate over the string with the foreach method and continue to get the following error: System.ArgumentException : Value does not fall within the expected range. The function is as follows: public static IDictionary<char, int> Count(string sequence) { IDictionary<char, int> Dna = new Dictionary<char, int>(); Dna.Add('A', 0); Dna.Add('C', 0); Dna.Add('G', 0); Dna.Add('T', 0); foreach(char c in sequence) { if(c != 'A' || c != 'C' || c != 'G' || c != 'T') { throw new ArgumentException(); } ++Dna[c]; } return Dna; } The stack trace identifies the line where the string is passed into it and line 20 which is the ++Dna[c] line. I am still learning C#, only a few days into it. This is from an exercises on another site.

5/31/2020 2:00:53 PM

William Owens

2 Answers

New Answer

+3

The if-statement in the foreach loop checks if 'c' is not equal to all of the characters (which it never will be) so the if always throws. I believe you want to check if it is not equal to any of the characters: if (c != 'A' && c != 'C' && c != 'G' && c != 'T') { throw new ArgumentException(); } I'm not familiar with C# so I don't know about the validity of ++Dna[c] on a dictionary. My guess would be that it's supposed to increment the dictionary index for the character matched by 'c'?

0

That was it my logic was incorrect. Thank you for reviewing that.