如何转换ListList< AnotherType>
本文关键字:List AnotherType SomeType 何转换 转换 | 更新日期: 2023-09-27 18:13:29
我有两个数据类型:
class MyDataType {
public int Id;
private int Field;
public String AnotherFieldOrProperty;
// + there are some methods
}
class MyDataTypeDescriptor {
public int Id;
public String Description;
}
我需要将List<MyDataType>
转换为List<MyDataTypeDescriptor>
:MyDataTypeDescriptor.Id = MyDataType.Id
MyDataTypeDescriptor.Description = MyDataType.ToString()
;
我想c#只需要一行代码就可以非常简单和快速地做到这一点,但是我不知道怎么做,因为我不熟悉这些高级技术。有人能帮帮我吗?
谢谢
应该这样做(其中myDataTypes
是您的List<MyDataType>
):
List<MyDataTypeDescriptor> myDataTypeDescriptors =
myDataTypes.Select(x => new MyDataTypeDescriptor
{
Id = x.Id,
Description = x.ToString()
}).ToList();
(from i in list1
select new MyDataTypeDescriptor { Id = i.Id, Description = i.ToString()).ToList();
如果您不想自己编写迭代器,可以使用automapper自动为您完成此操作。
您可以使用LINQ Select
方法:
List<MyDataType> list;
// Process list...
List<MyDataTypeDescriptor> result =
list.Select(x => new MyDataTypeDescriptor() { Id = x.Id, Description = x.ToString() }).
ToList<MyDataTypeDescriptor>();
或者如果你有一个MyDataTypeDescriptor
的构造函数,它接受一个Id
和一个Description
:
List<MyDataType> list;
// Process list...
List<MyDataTypeDescriptor> result =
list.Select(x => new MyDataTypeDescriptor(x.Id, x.ToString())).
ToList<MyDataTypeDescriptor>();
对于简单的转换,您可以像这样使用Select
方法:
List<int> lstA = new List<int>();
List<string> lstB = lstA.Select(x => x.ToString()).ToList();
对于更复杂的转换,可以使用ConvertAll
函数,如下所示:
List<int> lstA = new List<int>();
List<string> lstB = lstA.ConvertAll<string>(new Converter<int, string>(StringToInt));
public static string StringToInt(int value)
{
return value.ToString();
}
您可以使用LINQ
:
var listofMyDataTypeDescriptor = (from m in listOfMyDataType
select new MyDataTypeDescriptor()
{
Id = m.Id,
Description = m.ToString()
}).ToList();
您实际上不能转换它们,您必须遍历集合并为每个DataType创建一个新的描述符
var result = (from MyDataType m in listOfMyDataType select new MyDataTypeDescriptor
{
Id = m.Id,
Description = m.toString(),
}).ToList();
再添加一个方法
定义一个显式的用户类型转换MSDN
那么做
var newlist = MyDataTypleList.Cast<MyDataTypeDescriptor>().ToList();