这可能最终会成为一个快速的“无法完成”。但是我已经查看了,无法找到我特定查询的答案。
我的问题是我有一个用于保存学生详细信息的结构,现在说我有两个学生,一个叫Mike,另一个叫Dave,我想获得每个屏幕上的每个细节我在我的结构中有一个方法就像这样:
public struct student{
public String name, course;
public int year, studentno;
public void displayDetails(){
Console.WriteLine("Name: "+name);
Console.WriteLine("Course: "+course);
Console.WriteLine("Student Number: "+studentno);
Console.WriteLine("Year of Study: "+year);
Console.WriteLine("\n\nPress any key to Continue....");
Console.ReadKey();
}
}
现在要显示我可以使用的详细说明,Mike.displayDetails();或者Dave.displayDetails();
有没有办法可以要求用户输入名称,然后使用该名称来获得正确的学生?例如,我想使用:
Console.Write("Please enter students name: ");
String surname = Console.ReadLine();
然后以某种方式使用:
surname.displayDetails();
显示正确的学生,这可行吗?
答案 0 :(得分:6)
在字符串类型上使用extension method是可行的,但肯定不建议这样做。为什么不使用LINQ找到一个学生姓氏的学生?
List<Student> students
= new List<Student>
{
new Student { Surname = "Smith" },
new Student { Surname = "Jones" }
};
Student studentJones = students.FirstOrDefault(s => s.Surname == "Jones");
其他注意事项:
答案 1 :(得分:3)
你可以将它们放入字典中。
Dictionary<string, Student> dict = new Dictionary<string, Student>();
dict.Add("Dave", Dave);
dict.Add("Mike", Mike);
string surname = Console.ReadLine();
dict[surname].DisplayDetails();
顺便说一句,从字典中检索通常比查看列表(O(n))更快(O(1)),FirstOrDefault
执行。{/ p>
答案 2 :(得分:0)
创建一个类并从KeyedCollection派生。将密钥设置为学生的姓名。当每个学生被添加到集合中时,您只需致电:
Console.Write(myCollection[surname].DisplayDetails());
public class Students : KeyedCollection<string, Student>
{
// The parameterless constructor of the base class creates a
// KeyedCollection with an internal dictionary. For this code
// example, no other constructors are exposed.
//
public Students () : base() {}
// This is the only method that absolutely must be overridden,
// because without it the KeyedCollection cannot extract the
// keys from the items. The input parameter type is the
// second generic type argument, in this case OrderItem, and
// the return value type is the first generic type argument,
// in this case string.
//
protected override string GetKeyForItem(Student item)
{
// In this example, the key is the student's name.
return item.Name;
}
}