Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Dictionary<MyType>.ValueCollection to IList<MyType>

Tags:

c#

.net-2.0

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;
}
like image 217
C. Ross Avatar asked Mar 29 '10 19:03

C. Ross


3 Answers

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:

myDictionary.Values.ToList();

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(...) or list.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 return ICollection<T>. This is directly implemented by ValueCollection, which means you can just return your dictionary's values directly, with no copying:

private ICollection<MyType> ConvertToList(Dictionary<int, MyType>.ValueCollection valueCollection)
{
    return valueCollection;
}

(Granted, this method becomes really useless in this case - but I wanted to demonstrate it for you...)

like image 174
Reed Copsey Avatar answered Nov 10 '22 11:11

Reed Copsey


How about

Dictionary<int, MyType> dlist = new Dictionary<int, MyType>();
IList<MyType> list = new List<MyType>(dlist.Values);
like image 42
Adriaan Stander Avatar answered Nov 10 '22 10:11

Adriaan Stander


This is not possible.

A dictionary (including its Values collection) is an inherently unordered collections; its order will change based on the hashcodes of its keys. This is why ValueCollection doesn't implement IList<T> in the first place.

If you really wanted to, you could make a wrapper class that implements IList and wraps the ValueCollection, using a foreach loop in the indexer. However, it's not a good idea.

like image 2
SLaks Avatar answered Nov 10 '22 12:11

SLaks