【发布时间】:2018-06-30 10:44:02
【问题描述】:
我正在寻找一种更好的方法来执行以下操作。
using System;
using System.Collections;
Dictionary<int, string> namebyID = new Dictionary<int, string>();
Dictionary<string, int> idbyName = new Dictionary<string, int>();
Dictionary<string, string> valuebyName = new Dictionary<string, string>(); // users favorite dessert
/* Lets store information about "leethaxor" */
namebyID.Add(1234, "leethaxor");
idbyName.Add("leethaxor", 1234);
valuebyName.Add("leethaxor", "cake");
/* use case 1, I'm given an ID and i need the user's favorite dessert*/
if (namebyID.ContainsKey(1234))
{
string username;
namebyID.TryGetValue(1234, out username);
if (valuebyName.ContainsKey(username))
{
string dessert;
valuebyName.TryGetValue(username, out dessert);
Console.Write("ID 1234 has a username of " + username + " and loves " + dessert + "\n");
}
}
/* use case 2, I'm given a username and need to make sure they have a valid ID*/
if (idbyName.ContainsKey("leethaxor"))
{
int id;
idbyName.TryGetValue("leethaxor", out id);
Console.Write("username leethaxor has a valid ID of " + id + "\n");
}
我真的不想使用 3 个不同的字典,因为 id、username 和 value 都是相互关联的。将 key1(id) 和 key2(username) 散列在一起是行不通的,因为我只能得到其中一个,而不是两者。
【问题讨论】:
-
然后你应该创建一个包含所有这些相关信息的类。
-
请解释一下“更好的方法”中的“这个”是什么。让帮助变得更容易
-
这是您之前发布的同一个问题吗? stackoverflow.com/questions/48369716/…
-
@DavidG 似乎是相同的上下文,但显然 OP 已经使用了在该问题中向他/她建议的解决方案。所以这根本不是重复的。
-
为什么同时使用 ContainsKey 和 TryGetValue?
标签: c# dictionary key