CSharp - Create two dimensional indexer

Introduction

In the following program, we have used a dictionary to hold some employee name with their salaries.

Then we are trying to see the upper limit of their salaries.

If an employee is not found in our dictionary, we will say that the record is not found.

To use a Dictionary class, we need to include the following line in our program:

using System.Collections.Generic;

A dictionary is a collection and a <key, value> pair.

It uses a hash-table data structure to store a key with its corresponding values.

The following code shows how to use dictionary.

emp= new Dictionary<string, double>();
emp.Add("A",12345.87);

In the preceding two lines of code, we created a dictionary and then used its Add method.

In this dictionary, whenever we want to add data, the first parameter should be a string and the second one should be a double.

Note

We can have multiple indexers in the same class. The method signatures must be different from each other.

Indexers can be overloaded.

Indexers can take non-numeric subscripts.

Demo

using System;
using System.Collections.Generic;

class EmployeeRecord
{
    Dictionary<string, double> employeeWithSalary;
    public EmployeeRecord()
    {/*from   w ww .  j av  a  2  s.c  o m*/
        employeeWithSalary = new Dictionary<string, double>();
        employeeWithSalary.Add("A", 12345.87);
        employeeWithSalary.Add("S", 23456.21);
        employeeWithSalary.Add("R", 34567.21);
    }
    public bool this[string index, int predictedSalary]
    {
        get
        {
            double salary = 0.0;
            bool foundEmployee = false;
            bool prediction = false;
            foreach (string s in employeeWithSalary.Keys)
            {

                if (s.Equals(index))
                {
                    foundEmployee = true;//Employee found
                    salary = employeeWithSalary[s];//Employees
                                                   //actual salary
                    if (salary > predictedSalary)
                    {
                        //Some code
                        prediction = true;
                    }
                    else
                    {
                        //Some code
                    }
                    break;
                }
            }
            if (foundEmployee == false)
            {
                Console.WriteLine("Employee {0} Not found in our database.", index);
            }
            return prediction;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        EmployeeRecord employeeSalary = new EmployeeRecord();
        Console.WriteLine(employeeSalary["R", 25000]);
        Console.WriteLine(employeeSalary["A", 25000]);
        Console.WriteLine(employeeSalary["J", 10000]);
    }
}

Result

Related Topic