Reputation:
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;
}
}
Upvotes: 1
Views: 4139
Reputation: 112622
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>
.
Upvotes: 1
Reputation: 5607
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;
}
}
Upvotes: 5
Reputation: 3110
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 KeyValuePair
s.
Upvotes: 0