Rob
Rob

Reputation: 45771

Transforming Dictionary<T,U> to Dictionary<T, U.PropertyValue>

I'm in the process of re-writing some code whilst maintaining the external interface. The method I now need to work on has the following signature:

public Dictionary<int, string> GetClientIdNames()

This originally directly returned a backing field, after verifying that it was populating it and doing so if required. There's now a requirement for additional data to be stored, so the backing field is now as follows:

private Dictionary<int, Client> _clients;

public struct Client
{
    public int ClientId { get; set; }
    public string ClientName { get; set; }
    public string Password { get; set; }
}

So, other than simply looping using a foreach to construct a Dictionary<int, string> from Dictionary<int, Client> using the ClientName property of the Client, how could I perform this transformation on the fly?

Upvotes: 2

Views: 107

Answers (1)

Mark Byers
Mark Byers

Reputation: 838126

Use Enumerable.ToDictionary:

var clientNames = _clients.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ClientName);

Upvotes: 6

Related Questions