将一个类型的列表为另一种类型的列表在C#3.5 [英] Convert list of one type to list of another type in C# 3.5
问题描述
我有一个对象,通过ID和Name属性。
我有对象的列表,但我想将其转换为包含字符串列表命名的对象。
我猜有一些奇特的LINQ的方法,将放在对象变成列表的名称。
名单,LT ;字符串> myObjectNames = myObjectList?
如果你知道它具体是列表< T>
而不是其他集合类型,那么你可以使用 列表< T> .ConvertAll
:
在当前的元素转换
列表< T>
为另一种类型,并返回包含转换元素的列表
块引用>
例如:
列表<串GT; myObjectNames = myObjectList.ConvertAll(X => x.Name);
如果你只知道它是一个枚举类型但不一定是列表,那么你可以使用LINQ扩展方法
可枚举< T>。选择
和可枚举< T> .ToList
:列表<串> myObjectNames = myObjects.Select(X => x.Name).ToList();
I have an object, with ID and Name properties.
I have a list of the objects, but I want to convert it to a list of strings containing the name of the object. I'm guessing there's some fancy Linq method that will put the name of the object into the list.
List<string> myObjectNames = myObjectList.?
解决方案If you know it is specifically a
List<T>
and not another collection type then you can useList<T>.ConvertAll
:Converts the elements in the current
List<T>
to another type, and returns a list containing the converted elements.Example:
List<string> myObjectNames = myObjectList.ConvertAll(x => x.Name);
If you just know that it is an enumerable type but not necessarily a list then you can use the LINQ extension methods
Enumerable<T>.Select
andEnumerable<T>.ToList
:List<string> myObjectNames = myObjects.Select(x => x.Name).ToList();
这篇关于将一个类型的列表为另一种类型的列表在C#3.5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!