我正在寻找一种更好的方法来执行以下操作。
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)
一起哈希是行不通的,因为我只得到一个或另一个,而不是两个。
你应该明确地使用你自己的类来保存所有这些属于一起的信息。依赖不同的词典是一团糟,并且您放入这些词典的信息越多,就会变得非常复杂和复杂。
因此,在您的情况下,您可以创建一个类,我们将其称为Person
。每个Person
都有一个Id
、一个UserName
和一个Value
:
class Person
{
public int Id { get; set; }
public string UserName { get; set; }
public string Value { get; set; }
}
现在创建这些人的列表,例如:
var list = new List<Person> {
new Person { Id = 1234, UserName = "leethaxor", Value = "Cake" },
new Person { Id = 2, UserName = "Berta", Value = "AnotherValue" }
};
现在,您可以使用给定的Id
或给定的UserName
获得person
:
var aPerson = list.FirstOrDefault(x => x.Id = 1234);
或
var aPerson = list.FirstOrDefault(x => x.UserName = "leethaxor");
您应该明确了解面向对象编程的基础知识,这是关于对象及其行为的。
为什么不直接使用类?另外,使用 TryGetValue(( 而不是 ContainsKey((。哪个更有效:字典 TryGetValue 还是 ContainsKey+Item?
public class User
{
public int Id;
public string Name;
public string Value;
}
Dictionary<int, User> userById = new Dictionary<int, User>();