简体   繁体   English

如何在 c# 中的 object 列表中访问 object 列表

[英]how access list of object inside a list of object in c#

This is a teacher objects这是老师的对象

List<Teacher> teachername = new List<Teacher>(); Teacher teach = new Teacher(); teachername.Add(new Teacher("malathy", 2341, 987452165,0)); teachername.Add(new Teacher("shobhana", 3432, 4512789,1)); teachername.Add(new Teacher("indira", 6432, 243254564,2));

This is students object这是学生 object

 teach.studentlist.Add(new Student("manu", 1, "babu",2341)); teach.studentlist.Add(new Student("anu", 1, "sabu", 2341)); teach.studentlist.Add(new Student("hiba", 2, "vasu", 3432)); teach.studentlist.Add(new Student("shuba", 2, "gopi", 3432)); teach.studentlist.Add(new Student("indu", 3, "soman",6432)); teach.studentlist.Add(new Student("indira", 3, "Raman", 6432));

I want to separate and control the students by its numbers,ie,the 1 numbers students are under teacher malathy.2 number students are under shobhana.我想通过它的数字来分离和控制学生,即1个学生在老师马拉蒂之下。2个学生在sobhana之下。

Since we have no information about name's of objects properties, I'll just give them my own.由于我们没有关于对象属性名称的信息,所以我只给它们我自己的。

Option 1: foreach选项1:foreach

Update: As @DavideVitali mentioned in the comment section, it's and option that there is no implementation of the IEnumerbale , so I'll go with the foreach .更新:正如@DavideVitali 在评论部分提到的那样,可以选择没有实现IEnumerbale ,所以我将 go 与foreach

 foreach(var item in teach) { if(item.TeacherID == 1) { List<Student> MalathyStudents = new List<Student>(); MalathyStudents.Add(item); } if(item.TeacherID == 2) { List<Student> ShobhanaStudents = new List<Student>(); ShobhanaStudents.Add(item); } if(item.TeacherID == 3) { List<Student> IndiraStudents = new List<Student>(); IndiraStudents.Add(item); } }

Option 2: Linq.选项 2:Linq。

Note: You will have to import using System.Linq;注意:您必须using System.Linq;

I've changed the values of the last element in your objects, removed the 0 -我已经更改了对象中最后一个元素的值,删除了 0 -

 teachername.Add(new Teacher("malathy", 2341, 987452165, 1)); teachername.Add(new Teacher("shobhana", 3432, 4512789, 2)); teachername.Add(new Teacher("indira", 6432, 243254564, 3)); var MalathyStudents = teach.Where(s => s.TeacherID == 1).ToList(); var shobhanaStudents = teach.Where(s => s.TeacherID == 2).ToList(); var indiraStudents = teach.Where(s => s.TeacherID == 3).ToList();
var MalathysStudents = studentlist.Where(s=>s.TeacherId==1).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM