Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert object[] to List<string> in one line of C# 3.0?

ok I give up, how do you do this in one line?

public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    //List<string> fields = values.ToList<string>();
    //List<string> fields = values as List<string>;
    //List<string> fields = (List<string>)values;

    List<string> fields = new List<string>();
    foreach (object value in values)
    {
        fields.Add(value.ToString());
    }

    //process the fields here knowning they are strings
    ...
}
like image 398
Edward Tanguay Avatar asked May 15 '09 13:05

Edward Tanguay


2 Answers

Are you using C# 3.0 with LINQ? It's pretty easy then:

List<string> fields = values.Select(i => i.ToString()).ToList();
like image 137
Matt Hamilton Avatar answered Nov 01 '22 16:11

Matt Hamilton


If you have LINQ available (in .NET 3.5) and C# 3.0 (for extension methods), then there is quite a nice one liner:

var list = values.Cast<string>().ToList();

You're not going get anything much shorter that what you've posted for .NET 2.0/C# 2.0.

Caveat: I just realised that your object[] isn't necessarily of type string. If that is in fact the case, go with Matt Hamilton's method, which does the job well. If the element of your array are in fact of type string, then my method will of course work.

like image 40
Noldorin Avatar answered Nov 01 '22 17:11

Noldorin