[英]How to display a member from the list in Dictionary<int, List<string>>?
I have a Dictionary<int, List<string>>
where the key is a paper code and the list is a list of students enrolled in the paper. 我有一个
Dictionary<int, List<string>>
,其中的键是纸上的代码,列表是纸上的学生名单。
How do i display this list of students from a particular key ? 如何显示特定键的学生列表?
I have tried 我努力了
Console.WriteLine(myDictionary[targetkey])
but i just get this back 但是我回来了
System.Collections.Generic.List
1[System.String]` System.Collections.Generic.List
1 [System.String]`
myDictionary[targetkey]
will return the List<string>
at the given key and if you pass that to Console.WriteLine
, it will just call .ToString()
on it which will return System.Collections.Generic.List1[System.String]
. myDictionary[targetkey]
将返回给定键处的List<string>
,如果将其传递给Console.WriteLine
,它将仅对其调用.ToString()
,这将返回System.Collections.Generic.List1[System.String]
。 Actually any object you pass to Console.WriteLine
method, it will call ToString()
on it. 实际上,任何传递给
Console.WriteLine
方法的对象都将在其上调用ToString()
。
If youYou need to iterate over your dictionary and then print each one out. 如果您需要遍历字典,然后打印每本。
foreach(var thisList in myDictionary.Keys)
{
foreach(var thisStudent in thisList)
{
Console.WriteLine(thisStudent);
}
}
You can use TryGetValue
to make sure the key is there. 您可以使用
TryGetValue
来确保键在那里。 Then just loop through your List<string>
. 然后循环遍历您的
List<string>
。
var targetKey = 123;
List<string> students;
if(dictionary.TryGetValue(targetKey, out students))
foreach(var student in students)
Console.WriteLine(student);
You need to use for loop, 您需要使用for循环,
foreach (KeyValuePair<int, List<string>> dicItem in test)
{
foreach (string entry in dicItem.Value)
{
Console.WriteLine("Current entry for list {0}: {1}", dicItem.Key, entry);
}
}
Try 尝试
foreach ( var student in myDictionary[targetKey])
{
Console.WriteLine(student);
}
myDictionary[targetkey]
returns List<String>
so Covert List<String>
to string Array
myDictionary[targetkey]
返回List<String>
因此隐蔽List<String>
到string Array
Print result like below 打印结果如下
if(myDictionary.ContainsKey(targetkey))
Console.WriteLine(string.Join(",", myDictionary[targetkey].ToArray()));
Here is the solutions 这是解决方案
Dictionary<int, List<string>> dictionary = new Dictionary<int, List<string>>();
List<string> students = new List<string>();
//adding Elements to list
students.Add("Raees Ul Islam");
students.Add("Ubaid Ur Rehman");
//adding item to dictionary
dictionary.Add(1, students);
//Retriveing Data from Dictionary..
Console.WriteLine(((List<string>)dictionary[1])[0]);
Console.WriteLine("---------------");
//An Other Way to go through All Elements
List<string> studentsRetrived = dictionary[1];
foreach (var item in studentsRetrived)
{
Console.WriteLine(item);
}
Console.ReadLine();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.