You are here:

C#/How to convert a string List into int List

Advertisement


Question
Hello Murat;

In the following program i try to cast a list of string into a list of integer but i get a format exception, could you tell me what is wrong, thanks.

private void button1_Click(object sender, EventArgs e)
       {
         List<string> myStringList = new List<string>();
         List<int> myIntegerList = new List<int>();
         
         string[] firstArray = {"1", "2", "3", "4", "6", "9", "10"};
         int counter = 0;
         
         for (int i = 0; i < (firstArray.Length) - 4; i++)
         {
         for (int j = i + 1; j < (firstArray.Length) - 3; j++)
         {
         for (int k = j + 1; k < (firstArray.Length) - 2; k++)
         {
         for (int l = k + 1; l < (firstArray.Length) - 1; l++)
         {
         for (int o = l + 1; o < (firstArray.Length); o++)
         {
         dataGridView1.Rows.Add();
         dataGridView1.Rows[counter].Cells[0].Value = counter + 1;
         dataGridView1.Rows[counter].Cells[1].Value = firstArray[i];
         dataGridView1.Rows[counter].Cells[2].Value = firstArray[j];
         dataGridView1.Rows[counter].Cells[3].Value = firstArray[k];
         dataGridView1.Rows[counter].Cells[4].Value = firstArray[l];
         dataGridView1.Rows[counter].Cells[5].Value = firstArray[o];

         // I think the problem is here, but i do not know how to fix it.

         myStringList.Add(firstArray[i] + " " + firstArray[j] + " " + firstArray[k] + " " + firstArray[l] + " " + firstArray[o] + " ");

         counter++;
         }
         }
         }
         }
         }

         label1.Text = myStringList.Count.ToString();

         // Here i get a FormatException the Input string was not in a correct format.
       
         myIntegerList = myStringList.SelectMany(x => x.Split(' ')).Select(int.Parse).ToList();
       }

Answer
Hi there,

Why do you even need datagridview or arrays?


List<string> myStringList = new List<string>(){"1", "2", "3", "4", "6", "9", "10"};
List<int> myIntegerList = myStringList.Select(int.Parse).ToList();


Hope that helps,

Murat

C#

All Answers


Answers by Expert:


Ask Experts

Volunteer


Murat Mehmet

Expertise

I can help with questions about desktop and web programming in C#, including SOAP, XML, database managing, custom controls, security etc.

Experience

I have been developing web and especially desktop applications in C# and VB.Net for almost 5 years. My programming life has begun with VB6 long time ago, so its about 8 years that I am in this business.

Organizations
Was in R & D for 2 years in a popular Turkish technology website: cyber-warrior.com

Education/Credentials
2011 Computer Engineering graduation in University of Trakia in Turkey.

©2016 About.com. All rights reserved.