[英]How to lookup inner hashset in dictionary and return key value in c#?
I am trying to store signalR groups in Dictionary>我正在尝试将 signalR 组存储在字典中>
But i do not know how to lookup a string value in HashSet and return key string?但我不知道如何在 HashSet 中查找字符串值并返回键字符串?
var dict = new Dictionary<string, HashSet<string>>();
dict["GroupA"] = ["user1","user2","user3"];
dict["GroupB"] = ["user3", "user4"];
dict["GroupC"] = ["user4","user5","user6"];
I want to lookup for "user3" and it should returns ["GroupA","GroupB"].我想查找“user3”,它应该返回 ["GroupA","GroupB"]。 I do not know about that how to use dictionaries in c#.我不知道如何在 c# 中使用字典。 I have around ~20k groups and many of users in it.我有大约 2 万个群组,其中有许多用户。 Does it handle too much groups and users with singleton pattern (store in memory)?它是否使用单例模式(存储在内存中)处理过多的组和用户?
Hope someone help me with an working example.希望有人帮助我提供一个工作示例。 I am beginner here.我是这里的初学者。 Thanks!谢谢!
You need to iterate over the dictionary, and get all the keys that point to a hashset that contains the value you're looking for:您需要遍历字典,并获取指向包含您要查找的值的哈希集的所有键:
var matches = dict.Where(kvp => kvp.Value.Contains("user3"));
Explanation:解释:
You're asking for all the key-value pairs, where the Value (which we know is of type Hashset) contain the string you're looking for.您要求提供所有键值对,其中 Value(我们知道它属于 Hashset 类型)包含您要查找的字符串。
Update : to get just the keys from the key-value pairs, I believe you can do this:更新:要从键值对中获取键,我相信您可以这样做:
var matches = dict.Where(kvp => kvp.Value.Contains("user3")).Select(kvp => kvp.Key);
Further musing: if your use cases will always prioritize finding by user, perhaps you should invert the dictionary: have the user name be the key, and the value would be the groups the user belongs to.进一步思考:如果您的用例总是优先考虑用户查找,也许您应该反转字典:将用户名作为键,值将是用户所属的组。 That way, finding all groups for a user will be O(1).这样,查找用户的所有组将是 O(1)。
Answer will depend on the situation:答案将视情况而定:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.