字典与两把钥匙

Dim*_*tri 4 c# dictionary

通过字典中的两个键索引值的最佳方法是什么.例如:让学生使用唯一的Id(整数)和用户名(字符串)创建一个字典,其中包含由Id和username索引的学生类型的对象.然后在检索上使用Id或用户名.或者可能是词典不是很好的匹配?PS我知道元组,但没有看到如何在这种情况下使用它们.

编辑:作为使用两个键的替代方法,我可以创建一个由唯一分隔符分隔的id和username的字符串表示,然后使用正则表达式匹配键?!例:"1625 | user1"

Jon*_*nna 8

由于您希望能够通过其中任何一个进行检索,因此您需要两个词典.

假设Student类型是引用类型,Student每个学生仍然只有一个对象,所以不要担心.

最好将字典包装在一个对象中:

public class StudentDictionary
{
  private readonly Dictionary<int, Student> _byId = new Dictionary<int, Student>();
  private readonly Dictionary<string, Student> _byUsername = new Dictionary<string, Student>();//use appropriate `IEqualityComparer<string>` if you want other than ordinal string match
  public void Add(Student student)
  {
    _byId[student.ID] = student;
    _byUsername[student.Username] = student;
  }
  public bool TryGetValue(int id, out Student student)
  {
    return _byId.TryGetValue(id, out student);
  }
  public bool TryGetValue(string username, out Student student)
  {
    return _byUsername.TryGetValue(username, out student);
  }
}
Run Code Online (Sandbox Code Playgroud)

等等.

  • 并且你想在你的类中引入"索引器",如下所示:`public Student this [int id] {get {return _byId [id]; `和`public Student this [string username] {get {return _byUsername [username]; }.因为它很酷.它们的用法如下:`studDict [1336654]`或`studDict ["jeppesn"]`其中`studDict`是一些`StudentDictionary`对象. (2认同)