Dictionary with two keys

What is the best way to index values ​​with two keys in a dictionary. Example: having students with a unique identifier (integer) and username (string) creates a dictionary containing objects of type student indexed by identifier and username. Then use either the identifier or the username when searching. Or maybe the Dictionary is not suitable? Postscript I know tuples, but I don’t see how they can be used in this scenario.

EDIT: As an alternative to using two keys, I could create a string representation of both id and username, separated by a unique divider, and then match the keys with regex ?! Example: "1625 | user1"

+4
source share
4 answers

Since you want to be able to get through both, you will need two dictionaries.

Assuming the Student type is a reference type, you will still only have one Student object for each student, so don't worry about that.

It is best to wrap dictionaries in one object:

 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); } } 

And so on.

+8
source

You can use two dictionaries that you keep in sync, one that displays names for students and another that displays identifiers for students. The easiest way is to possibly wrap this in your own class that handles synchronization.

+3
source

No, Tuple helped you if you always had an Id and Username . You can use Dictionaries for each key. You can also implement your own Dictionary , which allows you to request both keys if their type is different:

 class MyDictionary : IDictionary<int, Student>, IDictionary<string, Student> { // full implementation } 
+2
source

Using the student object is a good option for what you want, but you have to override the equality functions (Equals and GetHashCode) to make it work correctly.

EDIT after reading this part more thoroughly. "Then use either the identifier or the username when searching." I believe my answer is not the best way. I would go with two dictionaries so +1 to @JonHanna.

0
source

Source: https://habr.com/ru/post/1432485/


All Articles