Indexing Data Using String Values in C#

public class PersonCollection : IEnumerable
{
  private Dictionary<string, Person> listOfPeople = new Dictionary<string, Person>();
 
  // This indexer returns a person based on a string index.
  public Person this[string name]
  {
    get { return (Person)listOfPeople[name]; }
    set { listOfPeople[name] = value; }
  }
 
  public void ClearPeople()
  { listOfPeople.Clear(); }
 
  public int Count
  { get { return listOfPeople.Count; } }
 
  IEnumerator IEnumerable.GetEnumerator()
  { return listOfPeople.GetEnumerator(); }
}
static void Main(string[] args)
{
  PersonCollection allPeople = new PersonCollection();
 
  allPeople["krish"] = new Person("Krish", "kanth", 40);
  allPeople["Mani"] = new Person("Mani", "Nath", 38);
 
  // Get "krish" and print data.
  Person kk = allPeople["krish"];
  Console.WriteLine(kk.ToString());
 
  Console.ReadLine();
}

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.