C# 将列表(对象)转换为列表(字符串)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/480399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert List(of object) to List(of string)
提问by Geoff Appleford
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)
有没有办法到转换List(of Object)
到List(of String)
C#或vb.net没有通过所有的项目迭代?(幕后迭代很好——我只想要简洁的代码)
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();
采纳答案by Mehrdad Afshari
Not possible without iterating to build a new list. You can wrap the list in a container that implements IList.
不迭代构建新列表是不可能的。您可以将列表包装在实现 IList 的容器中。
You can use LINQ to get a lazy evaluated version of IEnumerable<string>
from an object list like this:
您可以使用 LINQIEnumerable<string>
从这样的对象列表中获取延迟评估版本:
var stringList = myList.OfType<string>();
回答by marc_s
No - if you want to convert ALLelements of a list, you'll have to touch ALLelements 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.
您可以以不同的方式指定/编写迭代(foreach()......,或 .ConvertAll() 或其他),但最终,以一种或另一种方式,一些代码将迭代每一个元素并转换它。
Marc
马克
回答by Daniel Schaffer
If you want more control over how the conversion takes place, you can use ConvertAll:
如果您想更好地控制转换的发生方式,可以使用 ConvertAll:
var stringList = myList.ConvertAll(obj => obj.SomeToStringMethod());
回答by ctacke
You mean something like this?
你的意思是这样的?
List<object> objects = new List<object>();
var strings = (from o in objects
select o.ToString()).ToList();
回答by Ben Robbins
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.
您可以在构建 List(of object) 时进行字符串转换吗?这将是避免在创建 List(of object) 后枚举整个列表的唯一方法。
回答by Christer Eriksson
This works for all types.
这适用于所有类型。
List<object> objects = new List<object>();
List<string> strings = objects.Select(s => (string)s).ToList();