Cannot convert "string" to "int"

Asked

Viewed 1,107 times

0

<%
        foreach (System.Collections.DictionaryEntry entry in HttpContext.Current.Cache){
            HttpContext.Current.Cache.Remove((string)entry.Key);
        }

            foreach (int key in diamondMethodList)
            {

                Response.Write(string.Format("<option value=\"{0}\">{1}</option>", key, diamondMethodList[key]));
            }
        %>

Hello I’m having a small error in foreach, how do I convert? if I change the key int to key string from the following error in diamondMethodList[key]: it is not possible to implicitly convert type "string" to "int"

  • What is diamondMethodList? You are playing a string list in an integer.

  • you can’t know without knowing the diamondMethodList statement, but assuming it’s a string list do the conversion inside the loop with Int32.TryParse() or if you are sure that the list only contains numbers you can use Convert.ToInt32() as answered below

1 answer

0

HOW TO CONVERT STRING TO INT?

// Simples String para int
static void Main(string[] args)
{
    String text = "10";
    int a = Convert.ToInt32(text);
    int b = 10;
    int result = a + b;
    Console.WriteLine("Resultado: " + result);
    Console.ReadKey();
}

Output Result in Console Application:

Resultado: 20

Browser other questions tagged

You are not signed in. Login or sign up in order to post.