Cscience18
Cscience18

Reputation: 25

C# Convert Object to list<string>

I am trying to store the dates from the first row into a list string. How do I convert them to a list string from an object?

public List<string> populateDates(string id)
{
    List<string> dates = new List<string>();
    for (int i = 1; i < table.Columns.Count; i++)
    {
        object o = table.Rows[1][i];
        Console.WriteLine(o);
    }

    return dates;
}

Upvotes: 0

Views: 939

Answers (2)

PiotrWolkowski
PiotrWolkowski

Reputation: 8782

You can narrow down your method to a nice one-liner:

public List<string> populateDates(string id)
{
    return table[0].Select(d => d.ToString()).ToList();
}

Take whole first row. Select each item in it and execute ToString() on it. Wrap the result into a list.

As a side note, DateTime struct gives you quite a few methods to return different forms of date and time strings. Some of them: ToLongTimeString, ToShortDateString. Check MSDN for more details.

Also, if you are accessing the first row of your array then you should use the index 0 not 1 (as it is in your example).

Upvotes: 0

Donal
Donal

Reputation: 32713

You need to add the items to your List. You can call ToString to convert the item to a string. For example:

public List<string> populateDates(string id)
{
    List<string> dates = new List<string>();

    for (int i = 1; i < table.Columns.Count; i++)
    {
        dates.Add(table.Rows[1][i].ToString());
    }

    return dates;
}

Upvotes: 1

Related Questions