• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 198
  • Last Modified:

How to access members of my list by name instead of index

Hi there

I have a C# class that looks like the following:

namespace MyNameSpace.Data.Objects
{
    public class LevelsList : CollectionBase
    {
        public LevelListItem this[int index]
        {
              get { return ((LevelListItem)(List[index])); }
              set { List[index] = value; }
        }

       public int Add(LevelListItem levelListItem)
      {
            return List.Add(levelListItem);
      }      

    }
}

My LevelListItem class looks like this:

    public class LevelListItem
    {
      private int level;
      private string description;
      private bool selected;

      public int Level
      {
          get { return this.level; }
          set { this.level = value; }

      }

      public string Description
      {
          get { return this.description; }
          set { this.description = value; }

      }

      public bool Selected
      {
          get { return this.selected; }
          set { this.selected = value; }
      }

What I want to be able to do is to access the correct LevelListItem from my LevelsList using the
Description property of LevelListItem rather than its index position in the list.  So something like this:

        public LevelListItem Find(string description)
        {
            foreach LevelListItem li in List
            {
                if(li.Descrption == description)
                    return (LevelListItem) li;
            }
           
        }
 
   However this gives me 2 syntax errors - one hightlights LevelListItem after foreach and the second says it is expecting a ) after the List word??

Anybody any ideas.

Thanks
Sam
0
Samm1502
Asked:
Samm1502
1 Solution
 
sandsonCommented:
Hi Sam,

this is because you haven't used the correct syntax for the foreach instruction. Here is the correct syntax
       public LevelListItem Find(string description)
        {
            foreach(LevelListItem li in List)
            {
                if(li.Description == description)
                    return li;
            }
            
        }

Open in new window

0
 
Samm1502Author Commented:
Ahhh so obvious!  Thanks
0

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now