【问题标题】:What would be the most appropriate collection to use for this scenario?对于这种情况,最合适的集合是什么?
【发布时间】:2018-03-07 21:10:21
【问题描述】:

根据最新版本的 .NET/C#,最适合用于此场景的集合是什么?我需要返回组 ID 与用户 ID 的映射。因此,请考虑以下示例的映射,其中组 111 有 2 个用户 222 和 444:

111 222
111 444
555 222

KeyValuePair 不是最有效的 b/c 数据反映多对多关系。

【问题讨论】:

  • 你可以使用 Linq 做一个 groupBy
  • 从您的陈述中,“考虑如下示例的映射,其中组 111 有 2 个用户 222 和 444”,这意味着一对多关系,并使用 KeyValuePairs>,因此键为 111 的键值对将具有 222、444 的列表,而键为 555 的键值对将具有 222 的列表
  • 你如何获得这些数据?使用 Linq,您可以创建一个方便的 IGrouping
  • 还有 linq 的 ToLookup
  • 如果您需要同时查找两个 ID,您可以使用两个字典

标签: c# .net collections


【解决方案1】:

您想要的数据结构称为“multimap”、“multidictionary”或“multivaluedictionary”,具体取决于您询问的对象。

有很多这样的实现;做一个网络搜索,你会找到一些。例如:

https://blogs.msdn.microsoft.com/dotnet/2014/08/05/multidictionary-becomes-multivaluedictionary/

https://www.dotnetperls.com/multimap

等等。

【讨论】:

    【解决方案2】:

    很遗憾LookUp 类并未完全公开,但您可以使用 Linq 来创建它:

    public class GroupUserid {
        public int group;
        public int userid;
    }
    
    var rawdata = List<GroupUserid>();
    var groupMembership = rawdata.ToLookup(d => d.group, d => d.userid);
    

    然后您可以使用以下命令查找组的成员:

    var membersIn111 = groupMembership[111];
    

    【讨论】:

      【解决方案3】:

      如果您只想找出组中的用户以及特定用户是否最有效地在给定组中(即可能有数千个用户),但您不需要那么高效地确定什么单个用户所在的组,您也可以考虑使用

      Dictionary<int, HashSet<int>> users = new Dictionary<int, HashSet<int>>();
      
      // Adding a new group:
      users[newGroup] = new HashSet<int>();
      
      // Adding a new user to the group:
      users[newGroup].Add(newUser);
      
      // Then to find all users in a group:
      HashSet<int> usersInAGroup = users[aGroup];
      
      // If you want to know very fast if a specific user is in this group, then:
      if (usersInAGroup.Contains(aUser)) {/* yes, the given user is in this group */};
      

      HashSet 特别针对很多元素的 Contains() 操作进行了优化。

      【讨论】:

        猜你喜欢
        • 2023-03-11
        • 2011-03-01
        • 1970-01-01
        • 2016-01-06
        • 2011-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多