a developer's notes – a semi-technical web development BLOG

May 15, 2012

How to convert a List of Strings into a List of Ints?

Filed under: C# — Duy Nguyen @ 2:25 pm
Tags: , , , , , , ,

Just use the foreach loop to convert each element and add to a new list.

        private static void ConvertStringListToIntList()
        {
            List<string> myStringList = new List<string>(){"0", "1", "2", "20", "16"};
            
            //does not work the way we want because they are strings
            myStringList.Sort();

            foreach (object o in myStringList)
            {
                Console.WriteLine(o); //output 0,1,16,2,20
            }

            List<int> myintList = new List<int>();

            foreach (var stringNubmer in myStringList)
            {
                int number = Convert.ToInt32(stringNubmer);
                myintList.Add(number);
            }

            //sorts the way we want because they are ints now
            myintList.Sort();

            Console.Write("\n"); //new line
            foreach (object o in myintList)
            {
                Console.WriteLine(o); //output 0,1,2,16,20
            }
        }
Advertisements

1 Comment »

  1. Why not just use a lambda?

    myStringList.Sort((p1, p2) => Convert.ToInt32(p1).CompareTo(Convert.ToInt32(p2)));

    Comment by Jaime — June 30, 2012 @ 3:26 pm | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: