【问题标题】:I have list if Guids and i want to check if any of that guid is present in dictionary as a key我有 Guids 列表,我想检查字典中是否存在任何该 guid 作为键
【发布时间】:2014-05-06 16:40:23
【问题描述】:

我有

List<Guid> id

我的字典:

manager.DriveTimes.Containskey(id)

我如何检查是否有任何 id 作为字典中的键存在。 我想在不针对 List id 使用 for 循环的情况下一次性签入。

任何建议

【问题讨论】:

    标签: c# .net c#-4.0


    【解决方案1】:
    idList.Any(id => manager.DriveTimes.ContainsKey(id));
    

    【讨论】:

    • +1 绝对是使用 Dictionary 的ContainsKey的更好选择
    【解决方案2】:

    您可以使用 System.Linq 中的 Intersect 扩展。

    bool anyGuids = manager.DriveTimes.Keys.Intersect(id).Any()
    

    【讨论】:

      【解决方案3】:

      为了完整起见,这里有一些性能比较

              List<Guid> listA = new List<Guid>();
              for (int count = 0; count < 10000; count++)
              {
                  listA.Add(Guid.NewGuid());
              }
      
              List<Guid> listB = new List<Guid>();
              for (int count = 0; count < 10000; count++)
              {
                  listB.Add(Guid.NewGuid());
              }
      
              // Match by Any without matches.
              System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
              sw.Start();
              bool matchFound = listA.Any(item => listB.Contains(item));
              sw.Stop();
              Console.WriteLine("List Match {0}ms", sw.ElapsedMilliseconds);
      
              System.Collections.Generic.Dictionary<Guid, string> dictA = new System.Collections.Generic.Dictionary<Guid, string>();
              for (int count = 0; count < 10000; count++)
              {
                  dictA.Add(Guid.NewGuid(),"");
              }
      
              // Match by Key without matches.
              sw.Reset();
              sw.Start();
              matchFound = listB.Any(item => dictA.ContainsKey(item));
              sw.Stop();
              Console.WriteLine("Key Match {0}ms", sw.ElapsedMilliseconds);
      

      这些给出结果

              List Match 1095ms
              Key Match 1ms
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-07-16
        • 2011-07-25
        • 2012-06-15
        • 1970-01-01
        • 1970-01-01
        • 2011-11-03
        相关资源
        最近更新 更多