Share via


Add item at specific position on IDictionnary

Question

Monday, September 27, 2010 11:55 AM

Hi,

I would like to insert an item at a specific position using IDictionnary !!! this code does not compile

 :

 public class Product : DictionaryBase
    {
        public Product this[int index]
        {
            get
            {
                return ((Product)(Dictionary[index]));
            }
            set
            {
                Dictionary[index] = value;
            }
        }

        public bool Contains(Product product)
        {
            return Dictionary.Contains(product);
        }

        public int Add(Product Product)
        {
            return Dictionary.Add(Product);
        }

        public void Insert(int index, Product product)
        {
            Dictionary.Insert(index, product);
        }

        public void Remove(Product product)
        {
            Dictionary.Remove(Product);
        }
    }

 

All replies (2)

Monday, September 27, 2010 12:29 PM âś…Answered

You cannot add an item at a specified position using Dictionary

public bool Contains(Product product)
{
    return Dictionary.Contains(product);
}
public void Add(Product Product)
{
    Dictionary.Add("SomeKey", Product);
}
public void Remove(Product product)
{
    Dictionary.Remove("SomeKey");
}

And you need to provide a key to add or remove a particular product. you can also use Generic List.


Monday, September 27, 2010 2:26 PM

You can directly add this way

Dictionary<String, String> dictionaryString = new Dictionary<String, String>();
        dictionaryString.Add("FirtName", "Emmaneale");
        dictionaryString.Add("LastName", "Mendu");
        dictionaryString.Add("Address1", String.Empty);
        dictionaryString.Add("Address2", String.Empty);
        dictionaryString.Add("PhoneNumber", "1234567890");