Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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(); 
like image 358
Geoff Appleford Avatar asked Jan 26 '09 16:01

Geoff Appleford


People also ask

How do I turn a list object into a String?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

How do you turn List of objects to List of String in flutter?

We have 3 steps to convert an Object/List to JSON string: create the class. create toJson() method which returns a JSON object that has key/value pairs corresponding to all fields of the class. get JSON string from JSON object/List using jsonEncode() function.

How do you turn an object into a List?

//Assuming that your object is a valid List object, you can use: Collections. singletonList(object) -- Returns an immutable list containing only the specified object. //Similarly, you can change the method in the map to convert to the datatype you need.

How do I convert a List to a String in Java?

We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.


2 Answers

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>(); 
like image 141
mmx Avatar answered Oct 01 '22 08:10

mmx


This works for all types.

List<object> objects = new List<object>(); List<string> strings = objects.Select(s => (string)s).ToList(); 
like image 39
Christer Eriksson Avatar answered Oct 01 '22 10:10

Christer Eriksson