简体   繁体   English

如何在字典中查找内部哈希集并在 C# 中返回键值?

[英]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:答案将视情况而定:

  • If SQL is an option, then do this in SQL before loading.如果 SQL 是一个选项,则在加载之前在 SQL 中执行此操作。 It is way more efficient in general.一般来说,它的效率更高。
  • If you always need to search by user, flip the dictionary, listing groups by member.如果您总是需要按用户搜索,请翻动字典,按成员列出组。
  • If the lookup happens server-side, I would go with two dictionaries: 1 member by group, 1 group by member.如果查找发生在服务器端,我会使用两个字典:1 个成员一个组,1 个成员一个组。 That doubles memory usage, but if you can make these singletons serving all clients from same instances that should be a limited impact.这会使内存使用量增加一倍,但是如果您可以使这些单例为来自相同实例的所有客户端提供服务,那么影响应该是有限的。
  • If the lookup happens client-side than only load a mini list of groups for each user that they are a member of (either from SQL or from server-side singleton) No need to search any groups for other members in that case I would imagine.如果查找发生在客户端,则只为他们所属的每个用户加载一个小型组列表(来自 SQL 或来自服务器端单例)在这种情况下无需为其他成员搜索任何组,我想.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM