我有一份清单.
var dicAclWithCommonDsEffectivity = new Dictionary<string, List<int>>();
var list1 = new List<int>(){1,2,3};
var list2 = new List<int>(){2,4,6};
var list3 = new List<int>(){3,7,6};
var list4 = new List<int>(){8,7,6};
dicAclWithCommonDsEffectivity.Add("ab",list1);
dicAclWithCommonDsEffectivity.Add("bc",list2);
dicAclWithCommonDsEffectivity.Add("cd",list3);
dicAclWithCommonDsEffectivity.Add("de",list4);
Run Code Online (Sandbox Code Playgroud)
我想获取字典中的键,其中至少有一个匹配值与当前键列表.键"ab"(第一个列表).我应该得到:"ab","bc" and "cd".因为这些列表包含{1,2,3}中的一个匹配元素
有没有办法没有循环遍历字典值列表中的每个项目.
有没有办法没有循环遍历字典值列表中的每个项目.
有些东西必须循环 - 字典只能按键查找,除了第一次检查之外,你不会这样做.
你可以很容易地做到这一点:
private IEnumerable<string> GetMatchingKeys(
Dictionary<string, List<int>> dictionary, string key)
{
// TODO: Use TryGetValue if key might not be in dictionary
HashSet<int> elements = new HashSet<int>(dictionary[key]);
return dictionary.Where(pair => pair.Value.Any(x => elements.Contains(x)))
.Select(pair => pair.Key);
}
Run Code Online (Sandbox Code Playgroud)
这使用了Dictionary实现的事实IEnumerable<KeyValuePair<TKey, TValue>>- 因此该Where子句通过发现其值的任何元素是否与原始值的任何元素匹配来检查特定条目.该Select子句然后将该对投影到密钥.
如果你需要做这个有很多和你关心效率,另一种方法是建立从第二字典int来List<string>-基本上是一个反向映射.您需要保持这一点,但随后您可以轻松地获取映射到与给定键对应的每个值的所有"原始键",并且只是Distinct用来避免重复.
| 归档时间: |
|
| 查看次数: |
3163 次 |
| 最近记录: |