Search code examples
c#dictionarycontainskey

Dictionary<>.ContainsKey gives RuntimeBinderException


In .cshtml i want to check if a key exist in a Directory<int, Object> but i get always an error and can't find why.

This is my code:

@foreach (KeyValuePair<int, int> weekAndYear in @ViewBag.WeekAndYears)
{
    int key = int.Parse(weekAndYear.Value + "" + weekAndYear.Key);

    bool exist = ViewBag.Menus.ContainsKey(key);
}

The error I get:

The best overloaded method match for System.Collections.Generic.Dictionary<int,Object>.this[int] has some invalid arguments

When I use only the .Key or .Value it still works.

Edit - Solution

What the problem is, I don't know, but I have solved the problem with the following code:

foreach (KeyValuePair<int, int> weekAndYear in @ViewBag.WeekAndYears)
    {
        int key = int.Parse(weekAndYear.Value + "" + weekAndYear.Key);

        bool exist = ((Dictionary<int, Object>)ViewBag.Menus).ContainsKey(key);
}

Solution

  • What the problem is, I don't know, but I have solved the problem with the following code:

    foreach (KeyValuePair<int, int> weekAndYear in @ViewBag.WeekAndYears)
        {
            int key = int.Parse(weekAndYear.Value + "" + weekAndYear.Key);
    
            bool exist = ((Dictionary<int, Object>)ViewBag.Menus).ContainsKey(key);
    }