I’m using a Dictionary<int, MyType> in a class. That class implements a interface that requires an IList<MyType> to be returned. Is there a simple way to to cast the one to the other (without copying the entire thing)?
My current solution follows:
private IList<MyType> ConvertToList(Dictionary<int, MyType>.ValueCollection valueCollection)
{
List<MyType> list = new List<MyType>();
list.AddRange(valueCollection);
return list;
}
You’ll need to do a copy, but this is probably a good thing. In C# 2, your current code is almost the cleanest you can make. It would be improved by directly constructing your list off your values (
List<MyType> list = new List<MyType>(valueCollection);), but a copy will still be required.Using LINQ with C# 3, however, you would be able to do:
That being said, I would not (probably) try to avoid the copy. Returning a copy of your values tends to be safer, since it prevents the caller from causing problems if they attempt to modify your collection. By returning a copy, the caller can do
list.Add(...)orlist.Remove(...)without causing your class problems.Edit: Given your comment below, if all you want is an
IEnumerable<T>with a Count, you can just returnICollection<T>. This is directly implemented byValueCollection, which means you can just return your dictionary’s values directly, with no copying:(Granted, this method becomes really useless in this case – but I wanted to demonstrate it for you…)