【发布时间】:2021-09-06 20:20:08
【问题描述】:
我有一个包含嵌套列表的列表,我想将一个列表复制到一个新列表中以便我可以使用它。我可以通过指定索引来获得我想要的列表,但我无法将它复制到我想要使用的新列表中。我只是不太确定这样做的最佳方法是什么。
如何将内部列表复制到新列表中,以便可以将其用作普通列表?
这是我尝试过的。
public bool myMethod(List<Summary> summaries)
{
var listIndex = summaries[1];
List<newList> newLists = new List<newList>();
//this didn't work as ToList is giving error
List<newList> copy = listIndex.ToList(); //error: Summary does not contain a defination for ToList
//I tried this too it didn't work
var newCopy = indexer.Select(p => new newList
{
//my mapping
}).ToList();
return true;
}
一个包含所有列表的模型
public class Summary
{
public IEnumerable<Model1> mylist1 { get; set; }
public IEnumerable<Model2> mylist2 { get; set; }
public IEnumerable<Model3> mylist3 { get; set; }
public IEnumerable<Model4> mylist4 { get; set; }
}
我要复制到的新列表
public class newList
{
public string Name { get; set; }
public string Surname { get; set; }
//more properties
}
模型1
public class Model2
{
public string Name { get; set; }
public string Surname { get; set; }
//more properties
}
【问题讨论】:
-
model1包含什么内容? -
我已经在代码上更新了 Model1。
-
您正在使用索引访问摘要,但类型为
List<Summary>? -
我应该将它从 IEnumerable 更改为列表吗?
-
listIndex是Summary类型的对象。我想你可能打算做类似listIndex.mylist1.ToList();.
标签: c# list linq arraylist copy