alex10
alex10

Reputation: 2768

How to convert a dictionary into one condition

I have a method that I need to run only once. If a long condition is satisfied. For example:

 if (!("a" == "a" && "b" == "b"))
    RunMethod();

Main problem is that I can not know in advance how many keys a dictionary can have. And before what expression may or may not be a negation symbol. In the example, the negation symbol is the value of the dictionary.

var dict = new Dictionary<string, bool>
{
    { "a", false },
    { "b", true }
};

Option with one if is not very suitable because the method only needs to be run once:

if(dict.ContainsKey("a"))
    RunMethod();

UPD:

var dictFeature = new Dictionary<string, string>
{
    { "a", "a" },
    { "b", "a" }
};

var dict = new Dictionary<string, bool>
{
    { "a", false },
    { "b", true }
};

foreach (var i in dict)
{    
    if(dictFeature.ContainsKey(i.Key))
        RunMethod();
}

But if you write so then the method will be executed many times, as many keys in the dictionary.

Upvotes: 0

Views: 201

Answers (2)

Rafalon
Rafalon

Reputation: 4515

Why not something like the following with LINQ as suggested by @V0ldek:

var dictFeature = new Dictionary<string, string>
{
    { "a", "a" },
    { "b", "a" }
};

var dict = new Dictionary<string, bool>
{
    { "a", false },
    { "b", true }
};

if(dict.Any(kv => dictFeature.ContainsKey(kv.Key))
{
    RunMethod();
}

or more oldschool:

bool needsToExecute = false;

foreach (var i in dict)
{    
    if(dictFeature.ContainsKey(i.Key))
    {
        needsToExecute = true;
        break;
    }
}

if(needsToExecute)
    RunMethod();

Upvotes: 2

Mel Gerats
Mel Gerats

Reputation: 2262

If you only want to run the operation if all keys in dict are present in dictFeature:

if(dict.Keys.All(key => dictFeature.ContainsKey(key)))
    RunMethod();

Upvotes: 1

Related Questions