Dictionary<>.ContainsKey gives RuntimeBinderException
-
02-01-2020 - |
Question
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 2
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);
}
OTHER TIPS
Can you perhaps try using TryGetValue instead of ContainsKey and see if it works:
@foreach (KeyValuePair<int, int> weekAndYear in @ViewBag.WeekAndYears)
{
int key = int.Parse(weekAndYear.Value + "" + weekAndYear.Key);
Object outValue;
bool exist = Menus.TryGetValue(key, out outValue);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow