如何检查字典中的键是否包含值?

如何检查字典中的键是否包含值?

问题描述:

所以,我正在制作一个字典,每个键可以取多个值(即Dictionary< string,List< string>>)我的问题是,对于每个键,我希望它具有不同的值,也就是没有冗余在某个键的值中,所以我需要检查一个键是否包含字符串列表中的值

So, I'm making a dictionary for which each key can take multiple values(i.e Dictionary <string, List<string>>) My problem is that for each key I want it to have distinct values aka no redundancy in values for a certain key so I need to check if a key contains a value in the list of string

假设您的目标是确保每个'值字段您的词典中包含的键值对没有重复值:
Assuming your goal is to ensure the each 'Value field of the Key-Value Pairs contained in your Dictionary has no duplicate Values:
// required
// using System.Collections.Generic;

public class DistinctList : List<string>
{
    public new void Add(string value)
    {
        if (this.Contains(value)) return;

        base.Add(value);
    }
}

public class ValueDistinctDictionary : Dictionary<string, DistinctList>
{
    public void Add(string key, string value)
    {
        if (!this.ContainsKey(key))
        {
            base.Add(key, new DistinctList());
        }

        base[key].Add(value);
    }
}

// test in some method
// set break-points, examine 'vDict
ValueDistinctDictionary vDict = new ValueDistinctDictionary();

vDict.Add("hello", "goodbye");
vDict.Add("hello", "hello again");
vDict.Add("hello", "goodbye");

vDict.Add("hello1", "hello");
vDict.Add("hello1", "hello");
vDict.Add("hello1", "hello");


您只需阅读MSDN帮助。要检查元素是否在PIEBALDconsult建议的 HashSet 的实例中,您可以使用 System.Collections.Generic.HashSet< T>。包含(T)

https://msdn.microsoft.com/en-us/library/bb356440(v = vs.110).aspx [ ^ ]。



使用 Dictionary ,您可以使用 System.Collections.Generic.Dictionary< Key,Value> .ContainsKey(Key)

https://msdn.microsoft。 com / en-us / library / kw5aaea4(v = vs.110).aspx [ ^ ],

另见 https://msdn.microsoft.com/e n-us / library / a63811ah(v = vs.110).aspx [ ^ ]。



但是,在大多数情况下,它并不是最有效的因为更多时候你需要结合两个步骤:按键获取值并确定密钥是否已经存在。这是通过方法 TryGetValue 完成的:

https://msdn.microsoft.com/en-us/library/bb347013(v = vs.110).aspx [ ^ ]。



这就是全部。在提出这样的问题之前,请先阅读MSDN。



-SA
All you need is reading MSDN help. To check up if an element is in an instance of a HashSet advised by PIEBALDconsult, you can use System.Collections.Generic.HashSet<T>.Contains(T):
https://msdn.microsoft.com/en-us/library/bb356440(v=vs.110).aspx[^].

With Dictionary, you can use System.Collections.Generic.Dictionary<Key, Value>.ContainsKey(Key):
https://msdn.microsoft.com/en-us/library/kw5aaea4(v=vs.110).aspx[^],
see also https://msdn.microsoft.com/en-us/library/a63811ah(v=vs.110).aspx[^].

However, in most cases, it is not the most efficient way, because more often you need combine two steps: get the value by key and determine if the key already exists. This is done by the method TryGetValue:
https://msdn.microsoft.com/en-us/library/bb347013(v=vs.110).aspx[^].

That's all. Do read MSDN before asking questions like that.

—SA