如何复制列表< T>到另一个列表< T1> [英] How to copy list<T> to another list<T1>
问题描述
我有一个课程说T
class T
{
public string 名称{获取; set ;}
public string LName {获取; 设置;}
}
类T1
{
public string 名称{获取; set ;}
public string LName { get ; set ;}
}
列表< T> T_list = new 列表< T>
列表< T1> T1_list = new 列表< T1>
如何做复制
T1_list = T_list ????
我尝试过:
i可以使用foreach循环来实现这一点,例如
T1 t1 = null ;
foreach ( var item in T_list)
{
t1 = new T1();
t1.Name = item.name;
t1.LName = item.LName;
T1_list(t1);
}
但是我有更多的属性,所以你有更好的方法。
< blockquote>由于你有两个不同的类,我认为最简单的方法是在T1上创建一个构造函数,它接受T并从T构建T1。这将代码放在它所属的类中,你可以在任何地方使用它使用T1_list.Add(新T1(项目)。
T1_list(t1);
我根本不知道你认为这会做什么。另外,你的新陈述缺少括号。
试试文档:列表与LT; T> .ConvertAll(转换器和LT;吨,TOutput>)方法(System.Collections.Generic)| Microsoft Docs [ ^ ]
注意:如果字段,成员相同,则不需要创建两个具有不同名称的类!
例如:
class T
{
public string 名称{ get ; set ;}
public 字符串 LName { get ; set ;}
}
// 用法:
列表< T> firstlist = new 列表< T>();
列表< T> secondlist = new 列表< T>();
// 从第一个列表中复制数据
secondlist.AddRange (firstlist);
详情请见: List< T> .AddRange(IEnumerable< T>)Method(System.Collections.Generic)| Microsoft Docs [ ^ ]
i have a class say T
class T
{
public string Name{get;set;}
public string LName{get;set;}
}
Class T1
{
public string Name{get;set;}
public string LName{get;set;}
}
List<T> T_list = new List<T>
List<T1> T1_list = new List<T1>
How to do copy
T1_list = T_list ????
What I have tried:
i can do this using foreach loop like
T1 t1 = null;
foreach(var item in T_list)
{
t1 = new T1();
t1.Name = item.name;
t1.LName = item.LName;
T1_list(t1);
}
but i have more properties so is thee any better way to do this.
As you have two different classes, the easiest thing I think is to create a constructor on T1 that takes a T and builds the T1 from the T. That puts that code in the class where it belongs and you can use it anywhere by using T1_list.Add(new T1(item).
T1_list(t1);
I have literally no clue what you think this will do. Also, your new statements are missing the brackets.
Try the documentation: List<T>.ConvertAll(Converter<T,TOutput>) Method (System.Collections.Generic) | Microsoft Docs[^]
Note: you don't need to create two classes with different names if their fields, members are the same!
For example:
class T { public string Name{get;set;} public string LName{get;set;} } //usage: List<T> firstlist = new List<T>(); List<T> secondlist = new List<T>(); //copy data from first list secondlist.AddRange(firstlist);
For further details, please see: List<T>.AddRange(IEnumerable<T>) Method (System.Collections.Generic) | Microsoft Docs[^]
这篇关于如何复制列表< T>到另一个列表< T1>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!