将 List (对象)转换为 List (字符串)

有没有一种方法可以在 c # 或 vb.net 中将 List(of Object)转换为 List(of String),而不需要遍历所有项目?(幕后迭代很好-我只需要简洁的代码)

更新: 最好的方法可能就是重新选择

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

或者

myList.Select(i => i.ToString()).ToList();
182148 次浏览

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

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

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

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

You mean something like this?

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

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.

This works for all types.

List<object> objects = new List<object>();
List<string> strings = objects.Select(s => (string)s).ToList();
List<string> myList Str = myList.Select(x=>x.Value).OfType<string>().ToList();

Use "Select" to select a particular column