Geoff Appleford
Geoff Appleford

Reputation: 18832

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

Upvotes: 93

Views: 211476

Answers (7)

gaurav
gaurav

Reputation: 93

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

Use "Select" to select a particular column

Upvotes: 7

Christer Eriksson
Christer Eriksson

Reputation: 681

This works for all types.

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

Upvotes: 68

ctacke
ctacke

Reputation: 67168

You mean something like this?

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

Upvotes: 12

Ben Robbins
Ben Robbins

Reputation: 2630

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.

Upvotes: 1

Daniel Schaffer
Daniel Schaffer

Reputation: 57822

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

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

Upvotes: 27

marc_s
marc_s

Reputation: 754230

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

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

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

Upvotes: 95

Related Questions