考虑以下对象:
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 }
}
};
如何将此对象映射到以下形式的字典?
#key# -> #value#
"Test.Action1" -> 300
"Test.Action2" -> 200
"Test.Action3" -> 400
也就是一个Dictionary<string, int>
.
我对 LINQ 解决方案很感兴趣,但我无法解决它。
我正在尝试将每个操作映射到一个 KeyValuePair,但我不知道如何获取每个操作的父 Controller 的 Name 属性。
最佳答案
主要是 Controller 仍在 lambda 范围内:
var result = controller.Actions.ToDictionary(
a => string.Format("{0}.{1}", controller.Name, a.Name),
a => a.HttpCache);
关于c# - 使用 LINQ 将复杂对象映射到字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34534742/