none
Elements inside an Arraylist RRS feed

  • Question

  • Hey all!

    I got an Arraylist. It includes several elements.For example 4, 45, m, m34 . Now I want to check which element is a number and which element is a string. I know that I need a for loop based on the number of elements but I dont know how to check the criteria.

    if x is an arraylist then:

    for (int i=0; i< x.count;i++)
    {

        //Dont know what to do here!

    }

    Cheers!
    Sunday, June 22, 2008 12:17 PM

Answers

  • Hi

                ArrayList arr = new ArrayList();  
                arr.Add(4);  
                arr.Add("m");  
                arr.Add(45);  
                arr.Add("m34");  
                arr.Add("45m");  
     
                foreach (object obj in arr)  
                {  
                    if (obj.GetType() == typeof(int))  
                    {  
                        Console.WriteLine("This object is int and it's value = {0}", obj);  
                    }  
                    else 
                    {  
                        Console.WriteLine("This object is string and it's value = {0}", obj);  
                    }  
                }  
     
     
                // or  
                foreach (object obj in arr)  
                {  
                    Console.WriteLine("The type of this object is {0}", obj.GetType());  
                }  
     
                Console.ReadLine(); 

    Zaben
    • Marked as answer by Dave_Rose_82 Sunday, June 22, 2008 2:25 PM
    • Marked as answer by Dave_Rose_82 Sunday, June 22, 2008 2:25 PM
    Sunday, June 22, 2008 1:39 PM

All replies

  • Hi

                ArrayList arr = new ArrayList();  
                arr.Add(4);  
                arr.Add("m");  
                arr.Add(45);  
                arr.Add("m34");  
                arr.Add("45m");  
     
                foreach (object obj in arr)  
                {  
                    if (obj.GetType() == typeof(int))  
                    {  
                        Console.WriteLine("This object is int and it's value = {0}", obj);  
                    }  
                    else 
                    {  
                        Console.WriteLine("This object is string and it's value = {0}", obj);  
                    }  
                }  
     
     
                // or  
                foreach (object obj in arr)  
                {  
                    Console.WriteLine("The type of this object is {0}", obj.GetType());  
                }  
     
                Console.ReadLine(); 

    Zaben
    • Marked as answer by Dave_Rose_82 Sunday, June 22, 2008 2:25 PM
    • Marked as answer by Dave_Rose_82 Sunday, June 22, 2008 2:25 PM
    Sunday, June 22, 2008 1:39 PM
  • Thanks!:)
    Sunday, June 22, 2008 2:25 PM