C# Lists

April 2, 2009

C# Lists

Use of Lists in C#

What you will learn here:
1) Syntax is “List” where type can be a built-in type such as int, decimal, bool, string, or can be a class (either a .NET built-in class or one of your own).
2) How to add items to a List
3) How to use a “foreach” statement to loop through a list
4) Our specific example is a subroutine (method) that receives a List of numbers, and returns only the odd numbers in that List.

This video is a solution to a “quiz” I was given in an interview. A developer gave me this method signature, and asked me to scratch out the code to accomplish returning all the odd numbers in the list (at first I thought he said all the odd numbered items in the list).


   public List GetOddNumbers(List numList)
    {
      ...
    }

I had a “brain cloud” when doing this demo. I was thinking I could divide by 2 to find out if the number was even. I totally forgot about “modulo” division, which is what my subconscious was thinking. If you use a backslash instead of a forward slash, then the remainder will be returned. If you do modulo division dividing by 2, and the remainder is zero, then you have an even number, otherwise an odd number. That’s a more elegant way to do the odd/even test than what I did in the video below.

Code for you to copy:


namespace CSharpList
{
    class Program
    {
        static void Main(string[] args)
        {
            List numList = new List();
            numList.Add(5);
            numList.Add(6);
            numList.Add(7);
            numList.Add(20);
            numList.Add(21);
            numList.Add(22);
            numList.Add(23);
            List oddNumberList = GetOddNumbers(numList); 

            Console.WriteLine("Press enter to end:");
            Console.ReadLine(); 

        }

        // Extract odd numbers from a list of numbers
        public static List GetOddNumbers(List numList)
        {
            List returnOddNumberList = new List();
            foreach (int i in numList)
            {
                int x = i / 2;
                decimal y = (decimal) i / 2M;
                if (x != y)
                {
                    // we must have an odd number
                    returnOddNumberList.Add(i);
                    Console.WriteLine(
                       "Returning odd number = " + i);
                }

            }  // end foreach 

            return returnOddNumberList;
        }

    }
}

Video Demonstration:

Filed under C# Lists by Administrator

Permalink Print Comment