C#,如何从字典中的对象中获取值 [英] C#, how to grab values from object in dictionary
问题描述
//如果有人可以帮助我,我会很感激。
//非常乐意给你买咖啡。请给我你的电子邮件地址。
//不寻找任何免费信息。
//用它来创建学生对象没有问题。
公共学生(字符串优先,字符串最后)
{
FirstName = first;
LastName =最后一个;
}
//我在这本字典中存储对象没有问题。
//用于将学生添加到字典中。
Student.current.Add(Student.student_ID,已添加);
//实际字典。
public static Dictionary< int,Student> current = new Dictionary< int,Student>();
//以前让学生存储在列表中,在获取值时没有任何问题。
//现在我想打印存储在字典中的每个学生//所有值//与每个学生有关。
public static void printStudents()
{
foreach(KeyValuePair< int,Student>当前对)
{
Console.WriteLine({0 },{1},pair.Key,Student.FirstName);
Console.WriteLine({0},{1},pair.Key,Student.LastName);
}
}
//这是我的旧代码没有问题。
/ *
foreach(当前的var列表)
{
Console.WriteLine(\ nStudent ID:{0},listing.ID);
Console.WriteLine(名字:{0},listing.FirstName);
Console.WriteLine( 姓氏:{0} \ n,listing.LastN ame);
}
* /
我尝试了什么:
我觉得我已经尝试了一切。
也许在字典中,数据无法直接提取?
// If anyone can help me I'd appreciate it.
// More than happy to buy you a coffee. Just give me your email address.
// Not looking for any free information.
// used this to create the student object with no issues.
public Student(string first, string last)
{
FirstName = first;
LastName = last;
}
// i've had no issues storing the object in this dictionary.
// used to add student to dictionary.
Student.current.Add(Student.student_ID, added);
// actual dictionary.
public static Dictionary<int, Student> current = new Dictionary<int, Student>();
// Previously had Students being stored in list with no issues when grabbing values.
// Now I want to print each student stored in the dictionary with all values //pertaining to each student.
public static void printStudents()
{
foreach (KeyValuePair<int, Student> pair in current)
{
Console.WriteLine("{0}, {1}", pair.Key, Student.FirstName);
Console.WriteLine("{0}, {1}", pair.Key, Student.LastName);
}
}
// this is my old code had no issues.
/*
foreach (var listing in current)
{
Console.WriteLine("\nStudent ID: {0}", listing.ID);
Console.WriteLine("First Name: {0}", listing.FirstName);
Console.WriteLine("Last Name: {0}\n", listing.LastName);
}
*/
What I have tried:
I feel like I've tried everything.
Maybe in dictionaries, data can't be extracted directly ?
推荐答案
Console.WriteLine("{0}, {1}", pair.Key, pair.Value.FirstName);
Console.WriteLine("{0}, {1}", pair.Key, pair.Value.LastName);
这篇关于C#,如何从字典中的对象中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!