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

时间:2015-12-30 18:04:13

标签: c# linq dictionary

考虑以下对象:

(1..255).each do |i|
  r.all? {|i| i.size == 60} ? a << i : r[iter.next] << i
end

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

p x.size, y.size, z.size
#=> 60, 60, 60
p a.size
#=> 75

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 } } };

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

我正在尝试将每个操作映射到KeyValuePair,但我不知道如何获取每个操作的父控制器的Name属性。

4 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:1)

LINQ方法是使用Select方法将Actions列表投影到字典中。由于您在Controller个实例上进行了调用,因此您也可以访问控制器的Name

myController.Actions.ToDictionary(
    /* Key selector - use the controller instance + action */
    action => myController.Name + "." + action.Name, 
    /* Value selector - just the action */
    action => action.HttpCache);

如果要从几个控制器创建一个大型字典,可以使用SelectMany将每个Controller的项目投影到Controller + Action列表中,然后将其转换为列入字典:

var namesAndValues = 
    controllers.SelectMany(controller =>
        controller.Actions.Select(action =>
            { 
              Name = controller.Name + "." + action.Name,
              HttpCache = action.HttpCache
            }));
var dict = namesAndValues.ToDictionary(nav => nav.Name, nav => nav.HttpCache); 

答案 2 :(得分:1)

你可以试试这个:

var dico = controller.Actions
                     .ToDictionary(a => $"{controller.Name}.{a.Name}", 
                                   a => a.HttpCache);

第一个lambda表达式定位键,而第二个目标是词典条目的值。

答案 3 :(得分:0)

假设您在集合中有多个控制器,而不仅仅是示例代码中的一个var httpCaches = controllers.SelectMany(controller => controller.Actions.Select(action => new { Controller = controller, Action = action }) ) .ToDictionary( item => item.Controller.Name + "." + item.Action.Name, item => item.Action.HttpCache); 变量,并希望将所有操作放入单个字典中,那么您可以执行以下操作:< / p>

var controllers = new[] {
    new Controller()
    {
        Name = "Test1",
        Actions = new Action[] {
            new Action { Name = "Action1", HttpCache = 300 },
            new Action { Name = "Action2", HttpCache = 200 },
            new Action { Name = "Action3", HttpCache = 400 },
        }
    },
    new Controller()
    {
        Name = "Test2",
        Actions = new Action[] {
            new Action { Name = "Action1", HttpCache = 300 },
            new Action { Name = "Action2", HttpCache = 200 },
            new Action { Name = "Action3", HttpCache = 400 },
        }
    },
};

这适用于您设置数据的情况:

{{1}}