Convert list (object) to list (strings)

Is there a way to convert List(of Object) to List(of String) in C # or vb.net without iterating over all the elements? (Behind the scenes an iteration is ok - I just want a short code)

Update: The best way is probably just to make a new choice.

 myList.Select(function(i) i.ToString()).ToList(); 

or

 myList.Select(i => i.ToString()).ToList(); 
+63
generics c #
Jan 26 '09 at 16:29
source share
6 answers

It is impossible without the need to create a new list. You can wrap the list in a container that implements IList.

You can use LINQ to get a lazy evaluation version of IEnumerable<string> from a list of objects, for example:

 var stringList = myList.OfType<string>(); 
+68
Jan 26 '09 at 16:31
source share

This works for all types.

 List<object> objects = new List<object>(); List<string> strings = objects.Select(s => (string)s).ToList(); 
+31
Nov 14 '12 at 19:00
source share

If you need more control over how the conversion happens, you can use ConvertAll:

 var stringList = myList.ConvertAll(obj => obj.SomeToStringMethod()); 
+22
Jan 26 '09 at 16:33
source share

Do you mean something like this?

 List<object> objects = new List<object>(); var strings = (from o in objects select o.ToString()).ToList(); 
+8
Jan 26 '09 at 16:35
source share

No - if you want to convert ALL elements of a list, you will have to touch ALL elements of this list one way or another.

You can specify / write the iteration in different ways (foreach () ...... or .ConvertAll () or something else), but, in the end, one way or another, some code will iterate each element and convert it .

Mark

+3
Jan 26 '09 at 16:32
source share

Can you perform string conversion when creating a list (object)? This would be the only way to avoid listing the entire list after creating the list (object).

+1
Jan 26 '09 at 16:45
source share



All Articles