Special nested query in LINQ

I'm writting a graph algorithm and I'm almost there...

My algorithm stores several edge objects in a collection of edges, representing a path from initial vertex to final vertex. Thus, there should be also several paths between those vertexes (several collections of edge type), stored in another collection (in my class, callded "collswap").

Each edge is an object which have two vertexes: initial (v) and final (w), in this way:

dim manhattan as new vertex
dim brooklyn as new vertex
dim statenIsland as new vertex

dim brooklynBridge as new edge(brooklyn, manhattan)
dim route278 as new edge(statenIsland, brooklyn)

'calculates the path and stores the collections in a private property 'collswap'
me.returnPath(statenIsland, manhattan)

'in me.collswap (type collection) I have one collection (type 'system.collections.generic.list(of edge)) with two edges (route278 and brooklynBridge)

The graph is correctly calculated, but now I have to pick the best path. So, I need to query collswap in ways of:

  1. Retrieving only those paths which last edge contains the desired vertex in vertexW property ex: brooklynBridge.vertexW 'retrieves manhattan vertex (because my code can store a path which don't reaches the final vertex)

  2. Selecting the minor path between various located (the fewer ellements collection)

Would you help-me to build a good (and ellegant) Linq query to carry out these tasks?

Thank you!

Answers


In C#, sorry. I'm assuming collswap has a collection named paths, each of which is a List of edge.

Retrieving only those paths which last edge contains the desired vertex in vertexW property ex: brooklynBridge.vertexW 'retrieves manhattan vertex (because my code can store a path which don't reaches the final vertex)

List<List<edge>> goodPaths = collswap.paths.Where(path => path.Last() == manhattan);

This gives those paths that end at manhattan.

Selecting the minor path between various located (the fewer ellements collection)

List<edge> shortestGoodPath = goodPaths.OrderBy(path => path.Count()).First();

This gives the first good path, when the good paths are ordered by edge count; that is, this is the shortest good path.

You can combine the two operations if you want:

List<edge> shortestGoodPath = 
    collswap.paths
    .Where(path => path.Last() == manhattan)
    .OrderBy(path => path.Count())
    .First();

Need Your Help

Does Google Feed API add XML tags that are missing?

javascript xml rss google-feed-api

I have inherited a piece of Javascript that uses the Google Feed API.