确定Dictionary是否包含List中存在的条目(Determine if Dictionary has entries that exist in List)

我猜这个问题的答案很简单,但我无法弄明白。

我试图将List条目添加到Dictionary (在其他情况下,我只是检查Dictionary存在任何List条目。

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 ,我希望我能在这里做些什么。

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

I'm guessing the answer to this will be simple but I haven't been able to figure it out.

I am trying to add entries from a List into a Dictionary (and in other situations I'm just checking to see if any of the List entries exist in the 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 } }

Obviously RETURNALL isn't an actual method, this is where I get stuck. I know I can use Union to join up Lists and am hoping there is something I can do here.

Any help is appreciated! Thanks!

最满意答案

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

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

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

If you're looking for a pure LINQ solution:

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

This also has the advantage of using the dictionary's internal hash table efficiently, and will stop iterating the list as soon as one matching item is found.

更多推荐