tags:

views:

53

answers:

1

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?

+5  A: 

Use Enumerable.ToDictionary:

var clientNames = _clients.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ClientName);
Mark Byers
I would accept your answer *right now*, but I have to wait 10 minutes, apparently. Spot on and if I wasn't in the throes of migrating this module from 2.0 to 3.5, it would've already had the `using System.Linq` at the top of the file and the question would never have been asked. Thankyou! =)
Rob