none
getting index of array RRS feed

  • Question

  • Hi
      I have an array like this
    A[0] = "hi";  
    A[1] ="hello";  
    A[2] = "you"; 

      is there any way out to get the index of certain content of the array with a single statment  as below ??

    i = "hello".getindexfromA    // this is what i want

       I don't want to run a "for" loop compare "hello" with every element and return index...

    ----------

         It is true that i can have some function like

    int returnindex(string value)

    {
    compare value with every element of A unless found...

    if found, return index;

    }


       But while implementing it, i have to call as returnindex("hello");

    how do i make it possible so that i can call as "hello".returnindex ??  i mean add this function to the namespace string ...is that possible ??



    Tuesday, September 30, 2008 3:05 AM

Answers

  • Hi,

    Here's a single statement:

                var pos =   
                    A.Select(  
                        (greeting, position) =>   
                            new   
                            {   
                                Greeting = greeting,    
                                Position = position  
                            })  
                     .Where(greet => greet.Greeting == "Hello")  
                     .Single()  
                     .Position;  
     

    Or, you could write an extension method, like this:

            public static int ReturnIndex(this string source, string[] arr)  
            {  
                var pos =  
                    arr.Select(  
                        (greeting, position) =>  
                            new 
                            {  
                                Greeting = greeting,  
                                Position = position  
                            })  
                     .Where(greet => greet.Greeting == source)  
                     .Single()  
                     .Position;  
     
                return pos;  
            }

    and call it like this:

    "Hello".ReturnIndex(A) 

    Joe
    Free C# Tutorial @ http://www.csharp-station.com
    Tuesday, September 30, 2008 4:43 AM