Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping complex object to 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 map this object to 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 a LINQ solution but I can't manage to work around it.

I am trying to map each action to a KeyValuePair, but I don't know how to get each action's parent controller's Name property.

like image 843
Matias Cicero Avatar asked Feb 08 '23 04:02

Matias Cicero


1 Answers

The main thing is the controller is still in scope in the lambda:

var result = controller.Actions.ToDictionary(
  a => string.Format("{0}.{1}", controller.Name, a.Name),
  a => a.HttpCache);
like image 126
Amy B Avatar answered Feb 15 '23 02:02

Amy B