Matching a complex object to a dictionary using LINQ

Consider the following object:

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

How can I match this object with a dictionary of the following form?

#key# -> #value#
"Test.Action1" -> 300
"Test.Action2" -> 200
"Test.Action3" -> 400

That is a Dictionary<string, int>.

I am interested in LINQ solution, but I can not get around it.

I am trying to map each action to KeyValuePair, but I do not know how to get each property of the parent controller of each action.

+4
source share
4 answers

The main thing is that the controller is still in the lambda area:

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

LINQ Select . Controller, 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); 
+1

:

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

, - .

+1

, , controller , , - :

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

, :

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

Source: https://habr.com/ru/post/1622255/


All Articles