0

我创建了一个学生类型的列表。以下类是我使用的类;

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;
    }

}

现在我想从此对象访问特定学生的某些详细信息。假设我想获取学生的门牌号。我怎样才能做到这一点?我试图创建另一个列表,然后添加从GetStudents(). 但是,当我遍历它时,我只会得到对对象的引用。

//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());
  }
4

3 回答 3

3

您可以使用Linq选择您正在搜索的学生,然后访问其属性:

var student = GetStudents().FirstOrDefault(student => student.StudentId /* your student id here */>);
if (student != null)
{
    var houseNumber = student.Address.HouseNumber;
}
于 2013-10-07T09:53:39.320 回答
1

尝试这个

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);
}
于 2013-10-07T09:50:58.027 回答
0
Console.WriteLine(GetStudents()[0].HouseNumber.ToString());

(0可以是任何数字)

或(获取学生列表及其门牌号):

var houseNumbers = GetStudents().Select((student) => 
    String.Format("Student: {0} - {1}", 
    student.StudentId, student.Address.HouseNumber));
foreach(var entry in houseNumbers) Console.WriteLine(entry);
于 2013-10-07T09:56:37.873 回答