views:

4264

answers:

5

Is there a way to convert a list(of object) to a list(of string) in c# or vb.net without iterating through all the items? (Behind the scenes iteration is fine - I just want concise code)

Update: The best way is probably just to do a new select

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

or

myList.Select(i => i.ToString());
+6  A: 

Not possible without iterating to build a new list. You can wrap the list in a container that implements IList.

You can use LINQ to get a lazy evaluated version of IEnumerable<string> from an object list like this:

var stringList = myList.OfType<string>();
Mehrdad Afshari
Thanks Mehrdad, just what I was looking for.
geoff
Pretty good,thanks.
Braveyard
Instead of OfType(which filters the list) use Select(i => i.ToString())
geoff
@geoff: Depends on what you're looking for. If an element is null, i.ToString will fail. You might also consider Cast<string>();
Mehrdad Afshari
+3  A: 

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

You can specify / write the iteration in different ways (foreach()......, or .ConvertAll() or whatever), but in the end, one way or another, some code is going to iterate over each and every element and convert it.

Marc

marc_s
+3  A: 

If you want more control over how the conversion takes place, you can use ConvertAll:

var stringList = myList.ConvertAll(obj => obj.SomeToStringMethod());
Daniel Schaffer
This DOES iterate the list.
Mehrdad Afshari
Yes it DOES, but it's behind the scenes.
kenny
A: 

You mean something like this?

List<object> objects = new List<object>();
var strings = (from o in objects
              select o.ToString()).ToList();
ctacke
It doesn't return a list. It returns IEnumerable<string> :)
Mehrdad Afshari
Just do this:List<string> strings = (from o in objects select o.ToString()).ToList();
steve_c
Then it does iterate the list!
Mehrdad Afshari
I updated to add the (fairly obvious) ToList call.
ctacke
+1  A: 

Can you do the string conversion while the List(of object) is being built? This would be the only way to avoid enumerating the whole list after the List(of object) was created.

Ben Robbins