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


Question

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();
1
67
2/6/2019 4:19:03 PM

Accepted Answer

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>();
74
1/26/2009 4:31:42 PM

This works for all types.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon