[英]C# - Genereic List copy one row add Another row
我有一份学生名单,但条件是我需要复制一行并以较小的更改将其添加
例如:
具有以下特性的班级学生
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Section { get; set; }
public int Marks { get; set; }
}
因此,当标记= 90时遍历列表时,我需要复制该行并通过更新部分添加另一行
foreach (var item in studentData)
{
if(item.Section == 90)
{
//I need add some logic and update section and copy this item fully
//Add this modified item as new item to studentData
}
}
如果学生班最初有3个项目
1 "Sam" "A" 48
1 "John" "B" 68
1 "Broad" "A" 90
我的预期输出是
1 "Sam" "A" 48
1 "John" "B" 68
1 "Broad" "A" 90
1 "Broad" "C" 90
//Where i added one more row modifying the section
没有太多循环的最简单方法是什么? 卡住了!
我相信至少有例子的问题很清楚!!
谢谢
您不能将项目添加到要迭代的集合中,因此只需创建另一个列表,向其中添加副本,最后将列表中的项目添加到studentData
。
像这样:
var copies = new List<Student>();
foreach (var item in studentData)
{
if(item.Section == 90)
{
var copy = new Student();
copy.ID = item.ID;
copy.Name = item.Name;
copy.Marks = item.Marks;
copy.Section = // your updates to section
copies.Add(copy);
}
}
studentData.AddRange(copies);
如果您确实要复制Student
(因为我不确定这是否是好的设计),则可以使用以下LINQ查询:
list = list.AddRange(list.Where(x => x.Section == 90)
.Select(x => new Student()
{
// here set fields as you wish
}));
在构造函数中,您可以据此创建新用户。
您可能应该更改数据结构。 考虑对象,而不是表行。
例如:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public List<Grade> Grades { get; set; }
}
public class Grade
{
// Something
}
for (int i = 0; i< studentData.Count; i++)
{
var item = studentData[i];
if (item.Marks == "90")
{
studentData.Insert(i, new Student { Id = item.Id, Name = item.Name + "(smart one)", Section = item.Section, Marks = item.Marks});
i++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.