Convert List(of object) to List(of string)

C#vb.netGenerics

C# Problem Overview


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()).ToList();

or

myList.Select(i => i.ToString()).ToList();

C# Solutions


Solution 1 - C#

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>();

Solution 2 - C#

This works for all types.

List<object> objects = new List<object>();
List<string> strings = objects.Select(s => (string)s).ToList();

Solution 3 - C#

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

var stringList = myList.ConvertAll(obj => obj.SomeToStringMethod());

Solution 4 - C#

You mean something like this?

List<object> objects = new List<object>();
var strings = (from o in objects
              select o.ToString()).ToList();

Solution 5 - C#

List<string> myList Str = myList.Select(x=>x.Value).OfType<string>().ToList();

Use "Select" to select a particular column

Solution 6 - C#

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

Solution 7 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeoff ApplefordView Question on Stackoverflow
Solution 1 - C#mmxView Answer on Stackoverflow
Solution 2 - C#Christer ErikssonView Answer on Stackoverflow
Solution 3 - C#Daniel SchafferView Answer on Stackoverflow
Solution 4 - C#ctackeView Answer on Stackoverflow
Solution 5 - C#goroView Answer on Stackoverflow
Solution 6 - C#marc_sView Answer on Stackoverflow
Solution 7 - C#Ben RobbinsView Answer on Stackoverflow