确定Dictionary是否具有List中存在的条目

时间:2016-06-23 23:22:34

标签: c# list dictionary

我猜这个问题的答案很简单,但我还没能弄明白。

我正在尝试将List中的条目添加到Dictionary中(在其他情况下,我只是检查是否存在任何List条目Dictionary

private Dictionary<string, long> someDict;
public List<string> someList;

//someDict might have entries added here, someList is populated here

//Check if someDict currently has ANY entries from someList
if(someDict.ContainsKey(someList.RETURNALL)
{ 
    //may or may not add entries here depending on other conditions
    if(someOtherCondition){
       //Add any or all entries from someList into someDict using timestamp as second-column entry for someDict
    }
}

显然RETURNALL不是一个实际的方法,这是我被卡住的地方。我知道我可以使用Union加入Lists,我希望我能在这里做点什么。

任何帮助表示赞赏!谢谢!

6 个答案:

答案 0 :(得分:2)

如果您正在寻找纯粹的LINQ解决方案:

if (someList.Any(someDict.ContainsKey)) {
  ...
}

这也有利于有效使用字典的内部哈希表,并且一旦找到匹配的项目就会停止迭代列表。

答案 1 :(得分:1)

所以你要检查所有这些? 我认为你必须遍历每一个并找出,例如:

foreach(var i in someList)
{
if(someDict.ContainsKey(i)
{ 
    //may or may not add entries here depending on other conditions
    if(someOtherCondition){
       //Add any or all entries from someList into someDict using timestamp as second-column entry for someDict
    }
}
}

答案 2 :(得分:1)

它可能不是最有效的方法,但显然你可以为此编写自己的函数:

private bool ContainsAny(Dictionary<string, long> someDict, List<string> someList) {
 foreach(string listItem in someList) {
  if (someDict.containsKey(listItem)) {
   return true;
  }
 }
 return false;
}

这应该只检查给定的字典是否包含给定列表中的任何值。

答案 3 :(得分:0)

如果您需要检查someDict中的值。

long tmp;
foreach(var i in someList)
{
  if(someDict.TryGetValue(i, out tmp))
  { 
    //may or may not add entries here depending on other conditions
    if(someOtherCondition(tmp)){
       //Add any or all entries from someList into someDict using timestamp as second-column entry for someDict
    }
   }
}

答案 4 :(得分:0)

      private Dictionary<string, long> someDict;
      public List<string> someList;

        foreach (string t in someList.Where(t => someDict.ContainsKey(t)))
        {
              if(someOtherCondition){ }

        }

答案 5 :(得分:0)

采用nhouser9的想法,但通过使用模板extension method进行推广。

public static class DictionaryExtension
{
    public static bool ContainsAny<K, V>(this Dictionary<K, V> someDict, IEnumerable<K> someList)
    {
        foreach(K listItem in someList)
        {
            if(someDict.ContainsKey(listItem))
            {
                return true;
            }
        }
        return false;
    }
}

然后你可以写

if(someDict.ContainsAny(someList))

甚至

if(someDict.ContainsAny(new string[] {"a","b"}))