简体   繁体   中英

searching a dictionary within a dictionary c#

How can I check if the following collection of schemes has a certain string value? I've read several similar examples but nothing is really helping me. Many thanks,

Example what I need

    foreach(var item in data.Valuations)
    {
        if(item.Schemes.Contains("my string")) {
           // Do something 
        }
    }

The code

    public Valuation[] Valuations { get; set; }

    public IEnumerable<string> Schemes
    {
        get { return this.Values.Keys; }
    }

    public Dictionary<string, Dictionary<string, double>> Values { get; internal set; }

UPDATE

I've managed to do it using the following line of code.

    var model = new DetailViewModel 
    {
        model.Data = ...
    }

    // New bit

    model.Data.SelectMany(x => x.Schemes).Where(x => x == "my string");

However when looking at the model.Data it hasn't applied the filter. Am I missing something stupid? The 'my string' is located in the Schemes

The most efficient way of doing this is to use the ContainsKey method of the dictionary class :

if (Values.ContainsKey("my string")) 
{

}

If you really want to operate on your IEnumerable<String> Schemes property, then you can simply ensure that using System.Linq is at the top of your code, and .Contains will work exactly as in your question.

Try linq with SelectMany :

if(Values.SelectMany(x => x.Value.Keys).Any(x => x == "my string"))
{
   //do your stuff here
}

This will create a collection of all the keys from the inner dictionaries, which you can search with subsequent queries, in this example - with Any which will return true if the string was found.

Do you mean something like this:

    if(schemes.Any(x=>x=="my string")) 
    {
       // Do something
    }

you can use Any from LINQ to check if there is any element matching predicate -> here checking if there is any string equals to "my string".

You can use Contains only if using Lists so other solution is:

public List<string> Schemes
{
    get { return this.Values.Keys.ToList(); }
}

public Dictionary<string, Dictionary<string, double>> Values { get; internal set; }

and then

if(schemes.Contains("my string")) 
{
   // Do something
}

will be valid.

BUT I suggest using Linq instead of Contains on list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM