Reputation: 793
i am extracting 4 strings from a text, then i want to create an object with attributes from them, using the first string as the object name and the rest as attributes :
public void Load()
{
string line = File.ReadAllText(path);
foreach (var item in line)
{
string objectname = line.Split(':', '#')[1];
string Name = line.Split('$', ':')[2];
string Number = line.Split(':', '%')[3];
string Addres = line.Split(':', '&')[4];
StringBuilder StringBuilder = new StringBuilder();
}
}
should i use StringBuilder
for this? and how?
Upvotes: 0
Views: 84
Reputation: 66398
If you mean set value of properties based on the dynamic data you can use reflection.
Assuming this is your class:
public class Contact
{
public string Name { get; set; }
public string Number { get; set; }
public string Address { get; set; }
}
And this is possible format of the text file:
Name=John$Address=Canada$Number=111 Number=333$Name=Bob$Address=
Then such code will iterate the lines and create instance of Contact
for each, based on the values:
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
Contact contact = new Contact();
string[] parts = line.Split('$');
foreach (string part in parts)
{
string[] temp = part.split('=');
string propName = temp[0];
string propValue = (temp.Length > 1) ? temp[1] : "";
contact.GetType().GetProperty(propName).SetValue(contact, propValue, null);
}
}
Using this over the above sample two lines will create two instances with the given details.
Upvotes: 2