Question

I have a interface that can implement various collections and data types, it works fine with some collection but the dictionary is giving me issues, I'm guessing because the Dictionary is a little different and has key value pairs?

public interface IStructure
{
    void InsertRun<T> (T item);
    ICollection RetrieveSortedListRun<T>();
    T RetrieveItemRun<T>(T item);
}

class DictionaryRun : IStructure
{
    IDictionary<int, object> dictionary;

    public DictionaryRun()
    {
        dictionary = new Dictionary<int, object>();
    }

    public void InsertRun<T>(T item)
    {
        dictionary.Add(dictionary.Count + 1, item);
    }

    public ICollection RetrieveSortedListRun<T>()
    {
        return dictionary;
    }

    public T RetrieveItemRun<T>(T item)
    {
        return item;
    }
}
Was it helpful?

Solution

IDictionary<TKey, TValue> does not implement ICollection, it implements ICollection<KeyValuePair<TKey, TValue>>.

As is, if you changed your dictionary to be a IDictionary your code would compile.

However, it seems to me that your overall design of the interface and the object could be reworked.

public interface IStructure<T>
{
  void InsertRun(T item);
  ICollection<T> RetrieveSortedListRun();
  T RetrieveItemRun(T item);
}


class DictionaryRun<T> : IStructure<T>
{
  IDictionary<int, T> dictionary;

  public DictionaryRun()
  {
    dictionary = new Dictionary<int, T>();
  }

  public void InsertRun(T item)
  {
    dictionary.Add(dictionary.Count + 1, item);
  }

  public ICollection<T> RetrieveSortedListRun()
  {
    return dictionary.Values;
  }

  public T RetrieveItemRun(T item)
  {
    return item;
  }
}

OTHER TIPS

A Dictionary<TKey,TValue> implements ICollection<KeyValuePair<TKey,TValue>> not ICollection<TValue>. It seems that you are never using the key, so why not use a HashSet<T> instead? HashSet<T> implements ICollection<T>.


UPDATE

Your code line

dictionary.Add(dictionary.Count + 1, item);

lets me think that all you need is an ordered list. In contrast to a sorted list, which sorts the list according to a key, the ordered list keeps the original insert order. So you probably do best by using a List<T>.

Yes but Dictionary has a method to convert itself to a List, which implements ICollection:

public ICollection RetrieveSortedListRun<T>()
{
    return dictionary.ToList();
}

This will return a collection of KeyValuePairs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top