1

我有一个列表,其中包含具有名称、姓氏、id、年份等属性的 Student 类型的对象。我想要的是从具有特定索引的列表中删除特定的学生并将其放入另一个列表中。有没有办法这样做?例如:

        if (((mystudent[index].Year== 7)) {
              mystudent.RemoveAt(index);
           // now how I shall throw the Student to a new list
}

感谢您的信息。我现在的问题是我在单独的类中有 2 个列表。当我从列表中删除一个项目时,它的工作但当我想从其他类查看添加到列表中的项目时,我没有得到该项目。

public class SeniorStudentsClass
    {
        public List<Student> studlist = new List<Student>();

public void ViewStudents()
        {
            for (int i = 0; i < studlist.Count; i++)
            {               
                Console.Write(studlist[i].Id + "\t");
                Console.Write(studlist[i].Year + "\t");
                Console.Write(studlist[i].Name + "\t");
                Console.Write(studlist[i].Surname + "\t");
                Console.Write(studlist[i].DOB + "\t");
                Console.Write(studlist[i].Addr);
                Console.WriteLine();
            }

  public class JuniorStudentsClass
    {
       public List<Student> mystudent = new List<Student>();  
       SeniorStudentsClass sc = new SeniorStudentsClass();

        public void PromoteStudents(int index)
        {
            SearchItem(index);
            Console.WriteLine("current record:");
            Console.WriteLine("id is:" + mystudent[index].Id);
            Console.WriteLine("year is:" + mystudent[index].Year);
            Console.WriteLine("name is:" + mystudent[index].Name);
            Console.WriteLine("surname is:" + mystudent[index].Surname);
            Console.WriteLine("dob is:" + mystudent[index].DOB);
            Console.WriteLine("address is:" + mystudent[index].Addr);
            Console.WriteLine("year is:"+mystudent[index].Year);
            if (((mystudent[index].Year== 7)) || ((mystudent[index].Year == 8)))
            {
                var student = mystudent[index];
                mystudent.RemoveAt(index);
                sc.studlist.Add(student);
                Console.WriteLine("student promoted to senior student");

        }
4

3 回答 3

6

Linq 将使它更容易。

var moveables = mystudent.Where(x => x.Year == 7);

list2.AddRage(moveables);

mystudent.RemoveRange(moveables);

如果“另一个列表”尚不存在,您甚至可以仅用两行代码简化制作:

var list2 = mystudent.Where(x => x.Year == 7).ToList();

mystudent.RemoveRange(list2);
于 2012-12-14T15:04:19.983 回答
5

像这样的东西?

if (mystudent[index].Year == 7) 
{
    var studentToRemove = mystudent[index]; //get a reference to the student
    mystudent.RemoveAt(index); //Remove
    otherList.Add(studentToRemove); //Put student on another list
}

假设您正在遍历很多学生 - 并试图在特定年份移动所有学生 - 这样的事情可能会更好:

var yearSevenStudents = mystudent.Where(student => student.Year == 7).ToList();
于 2012-12-14T15:00:20.080 回答
-2

我希望这能回答你的问题,因为我不太明白,但尝试将学生复制到新表,然后删除旧表

于 2012-12-14T15:01:06.393 回答