开发者

Case Statement with Dictionary

Hi all i wrote the following code, what i am doing is i would like to use Switch case for my dictionary that exists but i am getting an error as

Can not implicitly convert stri开发者_如何转开发ng to bool

My code is as follows

List<string> lst = new List<string>();
lst.Add("Delete");
lst.Add("Reports");
lst.Add("Customer");

Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1, "Delete");
d.Add(2, "Reports");

    foreach (string i in lst)
    {
        if (d.ContainsValue(i))
        {
            switch (d.ContainsValue(i))
            {
                case "Delete": // Here i would like to compare my value from dictionary
                    //link1.NavigateUrl = "Reports.aspx";
                    HyperLink1.NavigateUrl = "Delete.aspx";
                    break;
            }


        }
        else
        {
            HyperLink2.Attributes["OnClick"] = "alert('Not a Valid User to Perform this operation'); return false";
        }
    }


d.ContainsValue(i)

returns boolean. When you do this:

case "Delete"

You try to compare the bool with a string, so it fails. You need to do this:

if (d.ContainsValue(i))
{
    switch (i)
    {
        case "Delete": // Here i would like to compare my value from dictionary
            //link1.NavigateUrl = "Reports.aspx";
            HyperLink1.NavigateUrl = "Delete.aspx";
            break;
    }
}


Try the following: switch (d[i])

It would probably be more efficient to use TryGetValue


the if inside the switch return a boolean value while the case says it must be a string

 switch (d.ContainsValue(i))
            {
                case "Delete": // Here i would like to compare my value from dictionary
                    //link1.NavigateUrl = "Reports.aspx";
                    HyperLink1.NavigateUrl = "Delete.aspx";
                    break;
            }

try this

switch (d[i])
                {
                    case "Delete": // Here i would like to compare my value from dictionary
                        //link1.NavigateUrl = "Reports.aspx";
                        HyperLink1.NavigateUrl = "Delete.aspx";
                        break;
                }


You can do something like this and avoid the switch all together:

var lst = new List<string>();
lst.Add("Delete");
lst.Add("Reports");
lst.Add("Customer");

Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1, "Delete");
d.Add(2, "Reports");

var hyperlinkMap = new Dictionary<string, string>()
{
    { "Delete", "Delete.aspx"},
    { "Reports", "Reports.aspx"}
};

foreach (var i in lst)
{
    if(d.ContainsValue(i))
    {
        HyperLink1.NavigateUrl = hyperlinkMap[i];
    }
    else
    {
        HyperLink2.Attributes["OnClick"] = "alert('Not a Valid User to Perform this operation'); return false";
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜