开发者

Checking if my dictionary<int, list<int>> has an item in the list

I am doing this right now:

foreach(..)
{
if(myDic.ContainsKey(car.ID) && myDic[car.ID].Contains(car.MfgID))
{

  // do som开发者_如何学Cething
}
}

I was wondering if I can perform the check, but check if it doesn't exist, and then just do a continue.

How would I do that? using a || or &&?

I cant' assume the key/value is there so I don't want it to crash.


foreach(..)
{
    if(!myDic.ContainsKey(car.ID) || !myDic[car.ID].Contains(car.MfgID))
    {
        continue;  
    }

    // do something
}
  • If car.ID is not a key of myDic then first condition is true and there is no evaluation of 2nd condition.
  • If car.ID is a key of myDic then the 2nd condition will be evaluated and it won't crash since the myDic[car.ID] has valid value.

If you have some logic in "do something" this way is useful since it uses the good access complexity of the dictionary. If "do something" is just selecting values so the whole loop is just a filter it's more elegant to use a LINQ query.


If you have LINQ available you could do something like this:

myDic.Any(kvp => kvp.Key == car.ID && kvp.Value.Contains(car.MfgID));

Figured I would add a little expansion, if you want to filter the list you could do the following:

var filteredDictionary = myDic.Where(kvp => kvp.Key == car.ID 
                                         && kvp.Value.Contains(car.MfgID));

foreach(...)
{
    ... //Only enumerating over items that match both conditions.
}


Another common way to do it is to use several simple guard clauses:

foreach (...)
{
    if (!myDic.ContainsKey(car.ID))
       continue;

    if (!myDic[car.ID].Contains(car.MfgID))
       continue;

    // do something actually
}

(it can improve readability sometimes)


What you have is fine, the right side of an && is not evaluated if the left side evaluates to false.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜