Thread: chapter11
View Single Post
  #3 (permalink)  
Old June 12th, 2004, 11:41 PM
Willem Willem is offline
Registered User
Points: 4, Level: 1
Points: 4, Level: 1 Points: 4, Level: 1 Points: 4, Level: 1
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2004
Location: , , .
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default

I realized that my code is not quite what it should be. I thought I was using the string indexer when I wasn't. Please replace in the collection code -

public Person this[ string name ]
        {
            get
            {
                int i;

                for (i = 0;i < List.Count;i++)
                {
                    Person tmp_person = (Person) List[i];

                    if ( tmp_person.Name == name )
                    {
                        i = List.Count;
                    }
                }

                if (i == List.Count)
                    return (Person)List[i];
                else
                    return(new Person("John Doe", 999));
            }
        }

with -

public Person this[ string name ]
        {
            get
            {
                int i;
                int j = 0;

                for (i = 0;i < List.Count;i++)
                {
                    Person tmp_person = (Person) List[i];

                    if ( tmp_person.Name == name )
                    {
                        j = i;
                        // I have to subtract one because the 'for' loop increments i and then checks to
                        // see if we reached the end of the loop. As a result, i will be one greater than
                        // it should be if I don't subtract one. A bit kludgy, I know.
                        i = List.Count -1;
                    }
                }

                if (i == List.Count)
                    return (Person)List[j];
                else
                    return(new Person("John Doe", 999));
            }
        }

In addition, in the client, replace this part -

// Look for a person using the string indexer.

            int count = 0;
            for (int i = 0; i < personCollection.Count;i++)
            {
                if (personCollection[i].Name == "Harold")
                    count += 1;
            }

            Console.WriteLine("I found {0} person(s) named Harold.", count);

with -

// Look for a person using the string indexer.
            string searchName = "Harold";

            Person tmp_person = personCollection[searchName];

            if (tmp_person.Name == "John Doe")
                Console.WriteLine("No person with the name {0} was found.", searchName);
            else
                Console.WriteLine("We found at least one person who is name {0}", searchName);

Reply With Quote