0

我有班级学生:

public class Student
    {
        public string Name { get; set; }
        public string Age { get; set; }
        public Student()
        {
        }
        public List<Student> getData()
        {
            List<Student> st = new List<Student> 
            {
                new Student{Name="Pham Nguyen",Age = "22"},
                new Student{Name="Phi Diep",Age = "22"},
                new Student{Name="Khang Tran",Age = "28"},
                new Student{Name="Trong Khoa",Age = "28"},
                new Student{Name="Quan Huy",Age = "28"},
                new Student{Name="Huy Chau",Age = "28"},
                new Student{Name="Hien Nguyen",Age = "28"},
                new Student{Name="Minh Sang",Age = "28"},
            };
            return st;
        }        
    }

我怎样才能在这个类中获取数据?(我的意思是 - 示例:我想显示 Name="Minh Sang",Age = "28")。

对不起这个问题。但我不知道在哪里可以找到它。

谢谢大家

4

5 回答 5

2

您可以使用 linq:

Student st = new Student();

var getStudent = from a in st.getData()
                      where a.Age == "28" & a.Name == "Minh Sang"
                      select a;

MessageBox.Show(getStudent.First().Age);
MessageBox.Show(getStudent.First().Name);
于 2012-04-24T00:26:14.737 回答
0

查看 List.Find 方法:

http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx

接下来尝试实现一个新方法:

public Student GetStudent(string name, int age)
于 2012-04-24T00:11:16.147 回答
0

调用 getData() 以获取学生列表。

使用 foreach 循环遍历列表。

在循环中,打印出学生的姓名和年龄。

于 2012-04-24T00:15:30.687 回答
0

也许您正在寻找DebuggerDisplay属性以在调试器中显示它?

[DebuggerDisplay("Name = {name}, Age={age}")]
public class Student {....}

因此,当您将鼠标悬停在 Student 类型的项目上时,它将以您想要的方式显示...

于 2012-04-24T00:31:26.623 回答
0

编辑 1: 将这些方法添加到您的课程中:

public Student getStudent(int age, string name)
{
    return this.getData().Find(s => Convert.ToInt32(s.Age) == age && s.Name.Equals(name));
}

public Student getByIndex(int index)
{
    Student s = null;
    // maxIndex will be: 7
    // your array goes from 0 to 7
    int maxIndex = this.getData().Count() - 1;
    // If your index does not exceed the elements of the array:
    if (index <= maxIndex)
        s  = this.getData()[index];
    return s;
}
  • int如果您将来需要评估,我将年龄转换><.

编辑2: 然后调用这样的方法:

    Student st = new Student();
    // s1 and s2 will return null if no result found.
    Student s1 = st.getStudent(28, "Minh Sang");
    Student s2 = st.getByIndex(7);

    if (s1 != null)
        Console.WriteLine(s1.Age);
        Console.WriteLine(s1.Name);
    if (s2 != null)
        Console.WriteLine(s2.Age);
        Console.WriteLine(s2.Name);
于 2012-04-24T00:46:14.517 回答