How to convert it:
var values = new List<object> { 1, 5, "eeE", MyEnum.Value };
To
var stringValues = new List<object> { "1", "5", "eeE", MyEnum.Value.ToString() };
But do it in fast way?
How to convert it:
var values = new List<object> { 1, 5, "eeE", MyEnum.Value };
To
var stringValues = new List<object> { "1", "5", "eeE", MyEnum.Value.ToString() };
But do it in fast way?
here's one approach
//original list
var values = new List<object> { 1, 5, "eeE", Colors.Red };
//List<string>
var stringValues = values.Select(x => x.ToString()).ToList();
//List<object>
var stringValuesAsObjectList = values.Select(x => x.ToString()).ToList<object>();
First, it's not clear whether your question is any different from Convert List(of object) to List(of string); if it is, you should clarify your particular situation.
The straight-forward solution is to use LINQ: var stringValues = values.Select(v => (object) v.ToString()).ToList();
Note the cast to object
to match your code above.
It's not clear why you'd want your result to be List<object>
instead of List<string>
. Also, you should prefer to work with IEnumerable<>
instead of converting to a List<>
. So the preferred code would be
var stringValues = values.Select(v => v.ToString());
If you're doing this type of thing a lot, you might find an extension method useful
static class ListExtensions
{
public static IEnumerable<string> AsStrings(this List<object> values)
{
return values.Select(v => v.ToString());
}
}
You would use it like:
var stringValues = values.AsStrings();
Depending on your needs, you may want more a more sophisticated string conversion than Object.ToString()
. Convert.ToString()
tries to first find IConvertable
and IFormattable
interfaces before calling ToString()
.
var stringValues = values.Select(v => Convert.ToString(v));