-2

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?

Nerf
  • 938
  • 1
  • 13
  • 30
  • 1
    Possible duplicate of [Convert List(of object) to List(of string)](http://stackoverflow.com/questions/480399/convert-listof-object-to-listof-string) – EpicKip Apr 14 '17 at 12:57

2 Answers2

2

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>();
Nino
  • 6,931
  • 2
  • 27
  • 42
  • you're right. In that case, i have edited my answer. – Nino Apr 14 '17 at 12:53
  • 1
    @Ðаn - Most likely the OP does not know what they actually want/need or did not express their actual intent correctly. – Igor Apr 14 '17 at 12:54
  • @Igor I'm guessing you're right, but I have edited my answer for nitpickers and downvoters :) – Nino Apr 14 '17 at 12:55
1

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));
Community
  • 1
  • 1
Ðаn
  • 10,934
  • 11
  • 59
  • 95