2012-12-14 201 views
1

我有一个列表,其中包含具有名称,姓氏,ID,年份等属性的Student类型的对象。我想要的是,我从具有特定索引的列表中删除特定的学生,把它放在另一个列表中。有没有办法呢? 例如:将项目从一个列表移动到另一个列表

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

感谢您的信息。我现在的问题是我有两个单独的班级名单。当我从列表中删除一个项目时,它的工作正常,但是当我想从另一个类中查看添加的项目到列表中时,我没有收到该项目。

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

     } 
+3

提示:你会希望你处置之前将它复制它。 –

+0

只需将对象从一个列表中复制到另一个列表中,然后删除它。像这样的东西:SecondList [i] = FirstList [i]; – jAC

回答

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 
} 

假设你经历了很多学生的loping - 并试图与特定的一年将所有的人 - 这样的事情可能会更好:

var yearSevenStudents = mystudent.Where(student => student.Year == 7).ToList(); 
+0

我可能需要更多的信息才能够帮助你... –

+0

@戴夫比什我编辑了这个问题。你可以帮我吗? –

-2

我希望这会回答你问题,因为我不太了解它,但尝试将学生复制到一个新表格,然后删除旧表格

+1

我猜他已经知道了。 他是imho要求代码来做到这一点。 – jAC

+0

有人可以帮我回答这个问题,因为我编辑了它 –

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