Sunscreen
Sunscreen

Reputation: 3564

Add strings to List<string[]> list

I'm new to C#, I need to do the following:

I need to declare a List

List<string[]> myList = new List<string[]>();

Now the conditions and adding to the list should work as follows (in pseudo code):

for int i = 0 to N
if nNumber == 1 add string[i] to myList[0]
else to myList[1]

In the end, I would have 2 members in my list, each member having several strings.

I am not sure how I can add these strings to the members as the method List(Of T).Add inserts members to the list and I do not want this.

Upvotes: 4

Views: 49027

Answers (4)

octopusgrabbus
octopusgrabbus

Reputation: 10685

In my csv parsing class, I have the following defined

enum gic_rpt_columns { AGYDIV, STS, GICID, LASTNAME, FIRSTNAME, COVERAGE, DESCRIPTION , PREMIUM, RUNDATE, BILMO, EMPLOYERPERCENT };

public class csv_parser
{
    .
    .
    .
    private string[]        m_column_headings;
    List<string[]>          m_csv_array = new List<string[]>();
    .
    .
    .

The following code will add my column headings and then the rows in the csv file

               using (TextFieldParser parser = new TextFieldParser(m_csv_path))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");

                    if (!parser.EndOfData)
                    {
                        m_column_headings = parser.ReadFields();
                        m_csv_array.Add(m_column_headings);
                    }

                    while (!parser.EndOfData)
                    {
                        string[] fields = parser.ReadFields();
                        m_csv_array.Add(fields);
                        m_row_count++;
                    }
                }

Upvotes: 1

Elias Hossain
Elias Hossain

Reputation: 4469

This can be also performed as List of List of string as below:

    List<List<string>> strList = new List<List<string>>();
    for (int i = 0; i < N; i++)
    {
        if (nNumber == 1)
            strList[0].Add(i.ToString());
        else
            strList[1].Add(i.ToString());
    }

Upvotes: 3

Heinzi
Heinzi

Reputation: 172210

From what I can see, you don't want a list of string arrays, you want a 2-element array of lists of strings:

var myList = new List<string>[] { new List<string>(), new List<string>() };

Now you should be able to implement the algorithm exactly as you specified.

Upvotes: 3

mjwills
mjwills

Reputation: 23819

        var myList = new List<string>[] { new List<string>(), new List<string>() }; 

        for (int i = 0; i <= 12; i++)
        {
            if (i == 1)
                myList.Last().Add(i.ToString());
            else
                myList.First().Add(i.ToString());
        }

Upvotes: 3

Related Questions