将项目从一个列表移动到另一个列表

时间:2012-12-14 14:58:07

标签: c#

我有一个列表,其中包含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");

        }

3 个答案:

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

答案 1 :(得分: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();

答案 2 :(得分:-2)

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