Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add object values through list of strings in c#

i am working with a project and facing a glitch i have a list of string values and have one class object and want to insert data to that object based on the list of string values. I am facing index out of bounds exception

Here is what i have tried

var modifications = new List<string>() {"1", "10", "100", "101", "102", "0"};

foreach (var item in modifications )
                {
                    obj.Mod1 = item[0].ToString();
                    obj.Mod2 = item[1].ToString();
                    obj.Mod3 = item[2].ToString();
                    obj.Mod4 = item[3].ToString();
                    obj.Mod5 = item[4].ToString();
                    obj.Mod6 = item[5].ToString();
                }

i want to put first value in list to Mod1 then second to Mod2 so on and so forth. Can any body tell me what will be the good approach here.
Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t need a loop.

obj.Mod1 = modifications[0];
obj.Mod2 = modifications[1];
obj.Mod3 = modifications[2];
obj.Mod4 = modifications[3];
obj.Mod5 = modifications[4];
obj.Mod6 = modifications[5];

The reason for the exception is that you loop the strings, so item is a string, for example "1", and then you access characters at index 5 which is out of the bounds of the string("5".Length==1).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading