I am parsing a file and I would like to store it in a lookup structure in a way that I can lookup with two keys.
I have a User Entity that has name, email and id, types are irrelevant.
I would like to store it in a Dictionary<User, id> so I can get the user id by looking up with User.
I also want the other way around, ie : Dictionary<Id, User>
I can create two structures and do the lookup. That s easy. I d like to do it with a single structure.
I am curious if I can do this with a single structure
I was thinking that I can do:
Dictionary<User, User> , then implement a IEqualityComparer<User>
Is there a better way to do this?
What would be the best practice to implement IEqualityComparer?
Whether you need to do this type of mapping or not, you can use a single dictionary to something like what you're asking for. Here's a rough sample:
var dict = new Dictionary<string, object>();
dict["ID_001"] = new User();
dict["USER_??"] = 001; // Need a unique user string to replace the "??"
Of course, you can make up any string you want. And if you want to wrap functions around things, you can avoid having to cast the object each time you get an item. (A static method might work better for you.)
User GetUser(int id, Dictionary<string, object> dict)
{
return (User)dict["ID_" + id];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With