Reputation: 23
I have a quick question about adding items to a new list So I have the following code:
Public struct testType
{
public string title
public string names
}
public List<testType> testlist= new List<testType>();
private void readTitles(string line)
{
string[] substrings = line.Split(new string[] { "\",\"" }, StringSplitOptions.None);
testType temp = new testType();
if (substrings.Length > 0)
for (int i= 0;i<substrings.Length;i++)
{
temp.title= substrings;
testlist.Add(temp);
}
else
temp.title= "";
}
private void readNames(string line)
{
string[] substrings = line.Split(new string[] { "\",\"" }, StringSplitOptions.None);
testType temp = new testType();
if (substrings.Length > 0)
for (int i = 0; i < substrings.Length; i++)
{
temp.names= substrings[i];
testlist.Add(temp);
}
else
temp.names= "";
}
So it can be seen that testlist will get populated with both the titles and names. It will populate with the titles and with names being null.Then names being populated with titles being null. How can I add the names to the created list without adding a new line to testlist with null values?
Upvotes: 0
Views: 69
Reputation: 61925
Is there any particular reason you are reading the titles and names in separate methods?
An obvious solution is to just read both at the same time within the same method, then you can create a single testType instance with both properties populated. I am assuming there will always be the same number of titles as there are names, and that the ordering in the strings is predictable:
public struct testType
{
public string title
public string name
}
public List<testType> testlist = new List<testType>();
private void readData(string titlesLine, string namesLine)
{
string[] titles = titlesLine.Split(new string[] { "\",\"" }, StringSplitOptions.None);
string[] names = namesLine.Split(new string[] { "\",\"" }, StringSplitOptions.None);
for (int i = 0; i < titles.Length; i++)
{
testType temp = new testType();
temp.title = titles[i];
temp.name = names[i];
testlist.Add(temp);
}
}
EDIT: An alternative (but less recommended) approach. If you really can't/won't combine the two methods into one, you can call them separately, and write the code as shown below, provided that you always call readTitles before readNames, and you always supply the data in the same order each time.
public struct testType
{
public string title
public string name
}
public List<testType> testlist = new List<testType>();
private void readTitles(string titlesLine)
{
string[] titles = titlesLine.Split(new string[] { "\",\"" }, StringSplitOptions.None);
for (int i = 0; i < titles.Length; i++)
{
testType temp = new testType();
temp.title = titles[i];
testlist.Add(temp);
}
}
private void readNames(string namesLine)
{
string[] names = namesLine.Split(new string[] { "\",\"" }, StringSplitOptions.None);
for (int i = 0; i < testlist.Count; i++)
{
testlist[i].name = names[i];
}
}
Upvotes: 2