I have a dictionary of dictionar开发者_如何学JAVAies, and I can't seem to figure out how to do a foreach loop on in the inner dictionary.
My collection:
Dictionary<int, Dictionary<int, User>>
So far I have:
foreach(User user in myDic[someKey]??)
nested foreach
foreach (var keyValue in myDic){
foreach (var user in keyValue.Value){
....
}
}
or a bit of linq
foreach (User User in myDic.SelectMany(i => i.Value).Select(kv=>kv.Value))
{
}
ordered by UserName
foreach (User User in myDic.SelectMany(i => i.Value)
.Select(kv=>kv.Value)
.OrderBy(u=>u.UserName))
{
}
foreach (KeyValuePair<int, Dictionary<int, User>> users in myDic) {
foreach (KeyValuePair<int, User> user in users.Value) {
...
}
}
foreach(User user in myDic[someKey].Values)
Is the literal answer to your question; though I'd generally recommend the use of the TryGet
method unless you're certain that someKey
is in the Keys collection of your dictionary.
Are you looking for this ?
var myDic = new Dictionary<int, Dictionary<int, string>>();
foreach(var item in myDic)
foreach (var subItem in item.Value)
{
Display(
subItem.Key, // int
subItem.Value); // User
}
//given: Dictionary<int, Dictionary<int, User>> myDic
foreach(KeyValuePair<int, Dictionary<int, User>> kvp in myDic) {
foreach(KeyValuePair<int, User> kvpUser in kvp.Value) {
User u = kvpUser.Value;
}
}
var users = myDic.Select(kvp => kvp.Value).SelectMany(dic => dic.Values);
foreach(User user in users)
{
...
}
精彩评论