C# - 通用列表复制一行添加另一行

时间:2014-11-19 09:27:46

标签: c# asp.net

我有一个学生名单,但条件是我需要复制一行并添加那一行稍作修改

例如:

具有以下属性的班级学生

public class Student
{      
    public int Id { get; set; }     
    public string Name { get; set; }
    public string Section { get; set; }
    public int Marks { get; set; }
}

因此,当循环遍历List时,如果marks = 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

在没有太多循环的情况下,最简单的方法是什么?我被困了!!

我相信这个问题至少与例子有关!!

由于

4 个答案:

答案 0 :(得分:1)

您无法将项目添加到您正在迭代的馆藏中,因此只需创建另一个列表,将副本添加到其中,最后将该列表中的项目添加到studentData。< / p>

这样的事情:

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);

答案 1 :(得分:1)

如果你真的想要复制Student(因为我不确定这是不是很好的设计),你可以使用以下LINQ查询:

list = list.AddRange(list.Where(x => x.Section  == 90)
                         .Select(x => new Student() 
                                      { 
                                         // here set fields as you wish
                                      }));

在构造函数中,您可以相应地创建新用户。

答案 2 :(得分:1)

您应该更改数据结构。 思考对象,而不是表格行。

例如:

public class Student
{      
    public int Id { get; set; }     
    public string Name { get; set; }
    public List<Grade> Grades { get; set; }
}

public class Grade
{      
    // Something
}

答案 3 :(得分:0)

        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++;
            }
        }
相关问题