2

I'm working on this puzzle https://www.codingame.com/ide/puzzle/skynet-revolution-episode-2

In this puzzle i have to block an agent from reaching nodes in a network, by each turn selecting a connection that I want to cut. I can only cut connections directly connected to a gateway.

I have a list of gateways List<Node> gateways. I already have initialized each node with a List<Node> Connections that contains the direct neighbors

Since gateways can be connected to more than one node, I am interested in the nodes that are exactly 1 node away from the gateways, so I can identify which one of those nodes (lets call them exitNodes) the agent is closest to.

How do I transform the list of gateways into a list of exit nodes? I tried

List<Node> exitNodes = gateways.Select(gw => gw.Connections).Select(node => node);

and this

List<Node> exitNodes = gateways.Select(gw => gw.Connections.Select(node => node));

I get the error

error CS0266: Cannot implicitly convert type System.Collections.Generic.IEnumerable<System.Collections.Generic.List<Node>>' toSystem.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?)

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
abinmorth
  • 527
  • 2
  • 8
  • 25

1 Answers1

2

You must use SelectMany.

If you use Select, then you get a Enumerable<List<Node>>, with SelectMany, you get only a List<Node>

List<Node> exitNodes = gateways.SelectMany(gw => gw.Connections).Select(node => node).ToList();

The answer in this post explains the difference between SelectMany and Select: https://stackoverflow.com/a/959057/5056173

Sean Stayns
  • 4,082
  • 5
  • 25
  • 35
  • I don't understand why i get a list though... i was expecting to get a list... with the first select i select the list from the gateway and with the second select i try to select the nodes from the lists – abinmorth Feb 11 '18 at 14:27
  • Please add the code to your answer, how you initialize your gateways variable and where you declare the variable, as well. – Sean Stayns Feb 11 '18 at 14:32
  • List gateways = new List(); also class Node { public List Connections {get; set;} = new List(); ... } – abinmorth Feb 11 '18 at 14:33
  • I have updated my answer.. Use SelectMANY instead of Select – Sean Stayns Feb 11 '18 at 14:47
  • I still get an error... error CS0266: Cannot implicitly convert type `System.Collections.Generic.IEnumerable' to `System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?) actually i don't really need a List... IEnumerable works as well :-) – abinmorth Feb 11 '18 at 15:34