1 c#
我有一个列表,其中包含Student类型的对象,其中包含姓名,姓氏,身份证,年份等属性.我想要的是我从具有特定索引的列表中删除特定学生并将其放入另一个列表中.有办法吗?例如:
if (((mystudent[index].Year== 7)) {
mystudent.RemoveAt(index);
// now how I shall throw the Student to a new list
}
Run Code Online (Sandbox Code Playgroud)
感谢您的信息.我现在的问题是我在单独的类中有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");
}
Run Code Online (Sandbox Code Playgroud)
Linq会让它变得更容易.
var moveables = mystudent.Where(x => x.Year == 7);
list2.AddRage(moveables);
mystudent.RemoveRange(moveables);
Run Code Online (Sandbox Code Playgroud)
如果"另一个列表"还不存在,您甚至可以简化为两行代码:
var list2 = mystudent.Where(x => x.Year == 7).ToList();
mystudent.RemoveRange(list2);
Run Code Online (Sandbox Code Playgroud)
像这样的东西?
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
}
Run Code Online (Sandbox Code Playgroud)
假设你希望通过很多学生 - 并尝试将所有学生搬到特定的一年 - 这样的事情可能会更好:
var yearSevenStudents = mystudent.Where(student => student.Year == 7).ToList();
Run Code Online (Sandbox Code Playgroud)