Edward Tanguay
Edward Tanguay

Reputation: 193302

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
    ...
}

Upvotes: 16

Views: 67750

Answers (6)

Suresh Deevi
Suresh Deevi

Reputation: 41

Array.ConvertAll(inputArray, p => p.ToString())

This converts an array of object type to array of string. You can convert to other type array by changing the lambda expression.

Upvotes: 4

Crispy
Crispy

Reputation: 5637

C# 2.0:

List<string> stringList = new List<string>(Array.ConvertAll<object,string>(values, new Converter<object,string>(Convert.ToString)));

Upvotes: 9

Daniel Earwicker
Daniel Earwicker

Reputation: 116674

One more variant that might be correct:

List<string> list = values.OfType<string>().ToList();

This will filter out any objects in the original list that are not string objects, instead of either throwing an exception or trying to convert them all into strings.

Upvotes: 4

Pat
Pat

Reputation: 5282

While not a one liner with respect to List<> declaration, gives you same effect without requiring Linq.

List<string> list = new List<string>();
Array.ForEach(values, value => list.Add(value.ToString()));

Upvotes: 2

Noldorin
Noldorin

Reputation: 147290

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.

Upvotes: 17

Matt Hamilton
Matt Hamilton

Reputation: 204139

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

List<string> fields = values.Select(i => i.ToString()).ToList();

Upvotes: 49

Related Questions