2013-10-07 132 views
0

我創建了一個學生類型列表。以下課程是我使用的課程;現在訪問列表元素。 C#

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

回答

3

您可以使用Linq選擇您正在搜索的學生,然後訪問其屬性:

var student = GetStudents().FirstOrDefault(student => student.StudentId /* your student id here */>); 
if (student != null) 
{ 
    var houseNumber = student.Address.HouseNumber; 
} 
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); 
} 
+1

因爲'Student'不會覆蓋'的ToString()'這隻會打印類的名稱。不是一個真正有用的答案。 – slugster

+0

@slugster當然,我假設你知道讀's.BlahBlah'等 –

+1

它將打印類的名稱**,而不是它的屬性。 – slugster

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