Dictionary Casting <int, List <User>

What is the most efficient way to drop Dictionary<int, List<User>>in Dictionary<int, IEnumerable<User>>?

The reason is because I have a method that creates Dictionary<int, List<User>>, but I would prefer not to return mutable Listto the calling code.

Should I project this dictionary into a new type?

+3
source share
3 answers

You can return IEnumerable, but under the hood it will be List. The developer can distinguish it before Listand add or remove elements

I think you're looking for Immutable Collections

, nuget, / ; , .

EDIT: IEnumerable

,

    var userDictionary = new Dictionary<int, List<User>>();
    userDictionary.Add(1, new List<User>
    {
        new User{ Name= "Joseph"},
    });
    IDictionary<int, IEnumerable<User>> newDictionary = userDictionary.ToDictionary(p => p.Key, p => p.Value.AsEnumerable());
    ((List<User>) newDictionary.Values.First()).Add(new User {Name = "Maria"});
    Console.WriteLine(newDictionary.Values.First().Count()); //now we have two users
+3

:

var userDictionary = new Dictionary<int, List<User>>();
IDictionary<int, IEnumerable<User>> newDictionary = userDictionary.ToDictionary(p => p.Key, p => p.Value.AsEnumerable());
+5

You will need to project this onto a new dictionary, for example

Dictionary<int, List<User>> myDictionary = ...;
Dictionary<int, IEnumerable<User>> resultingDictionary = myDictionary.ToDictionary(kvp => kvp.Key, kvp => (IEnumerable<User>)kvp.Value)

You cannot cast from Dictionary<int, List<User>>to Dictionary<int, IEnumerable<User>>because, if you could, the following is possible:

Dictionary<int, List<User>> myDictionary = ...;
// Still a reference to the original dictionary
Dictionary<int, IEnumerable<User>> castDictionary = myDictionary;

// If the line above was possible, what would this do? (A HashSet<T> is not a List<T>)
castDictionary.Add(5, new HashSet<User>());

You can also look at covariance and contravariance on interfaces to see where the constraints lie.

+1
source

All Articles