我正在控制台中跟踪值。两个人互相“决斗”,我用字典来记录名字和造成的伤害。
var duels = new Dictionary<string, string>();
duels.Add("User1", "50");
duels.Add("User2","34");
我试图将两个用户存储在同一个字典行中,因此可以验证用户 1 正在与 用户 2
决斗。这样,如果另一场决斗开始,它就不会干扰 User1
或 User2
。
duels.Add("KeyUser1","KeyUser2","50","34",.../*Other attributes of the duel*/);
我需要两把 key ,这样我就可以检查用户的伤害会去哪里。损坏总是会转到另一把 key ——反之亦然。 我可以做些什么来完成这项工作?
谢谢。
最佳答案
public class Duel
{
public string User1 {get; protected set;}
public string User2 {get; protected set;}
public Duel(string user1, string user2)
{
User1 = user1;
User2 = user2;
}
public HashSet<string> GetUserSet()
{
HashSet<string> result = new HashSet<string>();
result.Add(this.User1);
result.Add(this.User2);
return result;
}
//TODO ... more impl
}
让我们进行一些决斗吧。 CreateSetComparer
允许字典使用集合的值 进行相等性测试。
List<Duel> duelSource = GetDuels();
Dictionary<HashSet<string>, Duel> duels =
new Dictionary<HashSet<string>, Duel>(HashSet<string>.CreateSetComparer());
foreach(Duel d in duelSource)
{
duels.Add(d.GetUserSet(), d);
}
找到决斗:
HashSet<string> key = new HashSet<string>();
key.Add("User1");
key.Add("User2");
Duel myDuel = duels[key];
关于c# - 有两个键的字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9459796/