C# 在课堂上获取数据
我有一班学生:C# 在课堂上获取数据,c#,class,C#,Class,我有一班学生: public class Student { public string Name { get; set; } public string Age { get; set; } public Student() { } public List<Student> getData() { List<Student> st
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;
}
}
公共班级学生
{
公共字符串名称{get;set;}
公共字符串年龄{get;set;}
公立学生()
{
}
公共列表getData()
{
列表st=新列表
{
新学生{Name=“Pham Nguyen”,Age=“22”},
新学生{Name=“Phi Diep”,Age=“22”},
新学生{Name=“Khang Tran”,Age=“28”},
新学生{Name=“Trong Khoa”,Age=“28”},
新生{Name=“Quan Huy”,Age=“28”},
新生{Name=“Huy Chau”,Age=“28”},
新学生{Name=“Hien Nguyen”,Age=“28”},
新学生{Name=“Minh Sang”,Age=“28”},
};
返回st;
}
}
我如何在这门课上获取数据?(我的意思是-例如:我想用Name=“Minh Sang”,Age=“28”来展示)
对不起,这个问题。但我不知道在哪里可以找到它
谢谢大家查看列表。查找方法: 接下来,尝试实现一种新方法:
public Student GetStudent(string name, int age)
调用getData()以获取学生列表
使用foreach循环遍历列表
在循环中,打印出学生的姓名和年龄。您可以使用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);
也许您正在寻找在调试器中显示它的属性
[DebuggerDisplay("Name = {name}, Age={age}")]
public class Student {....}
因此,当您将鼠标悬停在Student类型的项目上时,它将以您想要的方式显示…编辑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;
}
你为什么不从学习基础知识开始,而不仅仅是复制粘贴你不懂的样本?+1。您应该一直在同一个LINQ语句中创建和填充控件…:)我是否可以发现数据只知道列表的编号(我的意思是此列表的编号形式为0到7-数据名称=“Huy Chau”,Age=“28”的编号形式为5)。我是否在我的课堂上添加了“公共字符串编号{get;set;}”呢?是的,你可以只添加公共字符串编号{get;set;},而在新学生{StudentNumber=“1”,Name=“Minh Sang”,Age=“28”}上,我可以发现数据只知道列表的编号(我的意思是这个列表的编号形式是0到7,数据名=“Huy Chau”,Age=“28”有编号5)。我在我的类中添加了“publicstringnumber{get;set;}”了吗?如果您想在列表中为您的用户添加一个额外的标识符(编号),那么您可以使用“Find”作为示例进行搜索。然而,用户列表中有索引,比如:位置0的用户,位置1的用户,等等,你也可以做一种“搜索”哦。因此,用户列表中有索引。我怎样才能找到那个职位?还有一个问题:你用另一种方式做过吗?(如果我有一个大班,我不想再“获取数据”)
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);