0

I need to take values from an array and assign them to a preexisting model but I don't know how to do that - I've tried looking on here and googling it but I can't find anything that makes sense to me or suits my needs (I will admit that I've probably looked at things that would work, but I don't understand enough to recognize that they would).

This is what I have so far:

 string AdditionalData = "Name: John, Age: 43, Location: California";
 string[] firstData = AdditionalData.Split(',');

 foreach (string dataString in firstData)
 {
     string[] temp = dataString.Split(':');
     //Do something here
 }

This just splits the string on the commas first then again on the colons, but how do I now get the values (specifically John, 43 and California) to assign them to a preexisting model called Person? Name/Age/Location already exist in the Person model, but they way I am receiving the data is different to my models (which I cannot change) and so I need to split out all the additional data and assign it to the correct model.

Any help at all would be greatly appreciated, and apologies if this is a bad question.

2
  • If you have Person class, simply do this: var person = new Person(); then do assignment to its properties like Person.Name = temp[x]; (x = array index number). If the string contains number and model property has int type, use either int.Parse, int.TryParse or Convert.ToInt32. Commented Aug 1, 2018 at 9:08
  • @TetsuyaYamamoto it never occurred to me to do that, thanks, I'll give it a shot! Hopefully it works! Commented Aug 1, 2018 at 9:23

1 Answer 1

1
string AdditionalData = "Name: John, Age: 43, Location: California";
string[] firstData = AdditionalData.Split(',');

Person person = new Person();
person.Name = firstData[0].Split(':')[1].Trim(); //John
person.Age = firstData[1].Split(':')[1].Trim(); //43
person.Location = firstData[2].Split(':')[1].Trim(); //California
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.