使用LINQ将复杂对象映射到字典

Mat*_*ero 4 c# linq dictionary

考虑以下对象:

Controller controller = new Controller()
{
    Name = "Test",
    Actions = new Action[]
    {
        new Action() { Name = "Action1", HttpCache = 300 },
        new Action() { Name = "Action2", HttpCache = 200 },
        new Action() { Name = "Action3", HttpCache = 400 }
    }
};
Run Code Online (Sandbox Code Playgroud)

如何将此对象映射到以下表单的字典?

#key# -> #value#
"Test.Action1" -> 300
"Test.Action2" -> 200
"Test.Action3" -> 400
Run Code Online (Sandbox Code Playgroud)

那就是一个Dictionary<string, int>.

我对LINQ解决方案感兴趣,但我无法解决它.

我试图将每个动作映射到KeyValuePair,但我不知道如何获取每个动作的父控制器的Name属性.

Amy*_*y B 6

主要的是控制器仍然在lambda的范围内:

var result = controller.Actions.ToDictionary(
  a => string.Format("{0}.{1}", controller.Name, a.Name),
  a => a.HttpCache);
Run Code Online (Sandbox Code Playgroud)