2011-11-04 123 views
2

我有两个数据类型:如何将List <SomeType>转换为列表<AnotherType>?

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#可以在一行代码中非常简单快速地完成,但是我不知道如何,因为我不熟悉这种高级技术。请有人帮助我吗?

感谢

回答

4

这应该这样做(其中myDataTypes是你List<MyDataType>):

List<MyDataTypeDescriptor> myDataTypeDescriptors = 
    myDataTypes.Select(x => new MyDataTypeDescriptor 
           { 
             Id = x.Id, 
             Description = x.ToString() 
           }).ToList(); 
0
(from i in list1 
select new MyDataTypeDescriptor { Id = i.Id, Description = i.ToString()).ToList(); 
0

可以使用automapper为你自动的做,如果你不想写迭代器自己..

0

您可以通过使用LINQ Select方法:

List<MyDataType> list; 
// Process list... 
List<MyDataTypeDescriptor> result = 
    list.Select(x => new MyDataTypeDescriptor() { Id = x.Id, Description = x.ToString() }). 
     ToList<MyDataTypeDescriptor>(); 

或者,如果你有MyDataTypeDescriptor一个构造函数的IdDescription

List<MyDataType> list; 
// Process list... 
List<MyDataTypeDescriptor> result = 
    list.Select(x => new MyDataTypeDescriptor(x.Id, x.ToString())). 
     ToList<MyDataTypeDescriptor>(); 
0

对于简单的转换,您可以使用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(); 
} 
0

你可以用LINQ做到这一点:

var listofMyDataTypeDescriptor = (from m in listOfMyDataType 
           select new MyDataTypeDescriptor() 
           { 
            Id = m.Id, 
            Description = m.ToString() 
           }).ToList(); 
0

你不能真正转化他们,你必须通过收集迭代和每个数据类型

var result = (from MyDataType m in listOfMyDataType select new MyDataTypeDescriptor 
{ 
    Id = m.Id, 
    Description = m.toString(), 
}).ToList(); 
0
创建一个新的描述符

只需添加一条路

定义明确的用户类型转换 MSDN

然后做

var newlist = MyDataTypleList.Cast<MyDataTypeDescriptor>().ToList(); 
相关问题