简体   繁体   English

列表的访问元素。 C#

[英]Accessing element of a List. C#

I have created a List of type Students. 我创建了一个学生类型列表。 The following classes are the ones I use; 以下是我使用的类;

public class StudentDetails
   {
   public class Address
    {
        public int HouseNumber{ get; set; }
        public string LineOne{ get; set; }
        public string LineTwo{ get; set; }
    }

    public class Student
    {
        public int StudentId { get; set; }
        public Address StudentAddress{ get; set; }
    }



    public List<Student> GetStudents()
    {
    private Address StudentOne = new Address{//details};
    private Address StudentTwo = new Address{//details};

    var students = new List<Student>();
    students.add(new Student {StudentId = 1, StudentAdress = StudentOne, //details});
    //more students
    return students;
    }

}

Now I would like to access certain details of a particular student from this object. 现在,我想从该对象访问特定学生的某些详细信息。 Say I want to get the House number of a student. 说我想获得一个学生的门牌号码。 How can i do that? 我怎样才能做到这一点? I attempted to create another list, then add the list returned from GetStudents() . 我试图创建另一个列表,然后添加从GetStudents()返回的列表。 However when i iterate through it , i only get references to objects. 但是,当我遍历它时,我只会得到对对象的引用。

//To access the List 

  StudentDetails student = new StudentDetails(); //create new instance
  for (int i = 0; i < student.GetStudents().Count; i++)
  {
            //Console.WriteLine(student[1].GetStudents());
  }

You can use Linq to select the student you are searching for and then access its properties: 您可以使用Linq选择要搜索的学生,然后访问其属性:

var student = GetStudents().FirstOrDefault(student => student.StudentId /* your student id here */>);
if (student != null)
{
    var houseNumber = student.Address.HouseNumber;
}

Try this 尝试这个

StudentDetails student = new StudentDetails(); //create new instance
foreach (var s in student.GetStudents())
{
   var id = s.StudentId;//use any properties using . operator
   Console.WriteLine(s);
}
Console.WriteLine(GetStudents()[0].HouseNumber.ToString());

(0 can be whatever number) (0可以是任何数字)

or (gets a list of students and their house numbers) : 或(获取学生及其门牌号码的列表):

var houseNumbers = GetStudents().Select((student) => 
    String.Format("Student: {0} - {1}", 
    student.StudentId, student.Address.HouseNumber));
foreach(var entry in houseNumbers) Console.WriteLine(entry);

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

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