-1

I'm using a string which contains multiple values inside: Example

string Response="John,13,1st,Mike,15,3st"...and so on

This 3 values need to be insert each value in separate class object. Example

class Students
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string  SchoolClass{ get; set; }
}

I need to use my list as example

 Students mItems = new List<Students>();
 mItems.Add(new Students() { Name = first string value,Age=second,SchoolClass=third....and so on

Or if it is simpler using my string with key value method

Name:John,Age:13,SchoolClass:1st ..... and so on

Dhi
  • 157
  • 3
  • 11

1 Answers1

0

String.Split and a for-loop:

List<Students> studentList = new  List<Students>();
string[] tokens = Response.Split(',');
for(int i  = 0; i <= tokens.Length - 3; i+=3)
{
    Students s = new Students {Name = tokens[i], Age = tokens[i + 1], SchoolClass = tokens[i + 2]};
    studentList.Add(s);
} 
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thank you nice example! – Dhi Sep 25 '18 at 12:50
  • @iBug: i noticed and flagged as spam. Btw, why there is there still no way to PM/notify someone? – Tim Schmelter Sep 26 '18 at 09:31
  • @iBug: then you don't need to comment on a random post if you want to talk to someone. Especially because this isn't related to the question or answer and it's not interesting for others. – Tim Schmelter Sep 26 '18 at 09:39
  • @TimSchmelter I'm fine with deleting these comments afterwards. I just like to remind others of inappropriate actions taken. – iBug Sep 26 '18 at 09:46
  • @iBug: sure, that workaround "works" but i don't understand why SO doesn't let communicate users directly (you could block someone if you get annoyed). – Tim Schmelter Sep 26 '18 at 10:06
  • @TimSchmelter Possible Meta answer: *Repeat after me: Stack Overflow is not a social network* – iBug Sep 26 '18 at 10:07