将Dictionary <T,U>转换为Dictionary <T,U.PropertyValue>

Rob*_*Rob 2 c# dictionary

我正在重新编写一些代码,同时保持外部接口.我现在需要处理的方法具有以下签名:

public Dictionary<int, string> GetClientIdNames()
Run Code Online (Sandbox Code Playgroud)

这最初直接返回一个后备字段,在验证它正在填充它并在需要时这样做.现在需要存储其他数据,因此支持字段现在如下:

private Dictionary<int, Client> _clients;

public struct Client
{
    public int ClientId { get; set; }
    public string ClientName { get; set; }
    public string Password { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

所以,除了简单地使用a foreach来构造a Dictionary<int, string>来Dictionary<int, Client>使用它的ClientName属性之外,Client我怎么能动态地执行这个转换呢?

Mar*_*ers 6

用途Enumerable.ToDictionary:

var clientNames = _clients.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ClientName);
Run Code Online (Sandbox Code Playgroud)