访问列表的元素.C#.

本文关键字:元素 列表 访问 | 更新日期: 2023-09-27 18:34:23

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

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

访问列表的元素.C#.

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

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

试试这个

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 可以是任意数字)

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

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