Assuming the βindexβ has nothing to do with ordering (just an identifier), let's say declared in this way:
public class Node { public int ID { get; set; } public int? PredID { get; set; } }
You can then create a map from predecessor to successor, and then follow the links. However, this is not pure LINQ, but readable and efficient enough:
public static LinkedList<int> GetLinkedList(IEnumerable<Node> nodes) { if(nodes == null) throw new ArgumentNullException("nodes"); return new LinkedList<int>(GetOrderedNodes(nodes.ToList())); } private static IEnumerable<int> GetOrderedNodes(IEnumerable<Node> nodes) {
EDIT : here is a terribly inefficient but functional solution.
The idea is that the index of the element should be 1 + its predecessor index, which is easy to specify recursively. The base, the case, of course, is the head - a node, whose predecessor ID is null .
static LinkedList<int> GetLinkedList(IEnumerable<Node> nodes) { return new LinkedList<int> ( from node in nodes orderby GetIndex(nodes, node) select node.ID ); } static int GetIndex(IEnumerable<Node> nodes, Node node) { return node.PredID == null ? 0 : 1 + GetIndex(nodes, nodes.Single(n => n.ID == node.PredID)); }
It is possible to slightly improve the second solution by first creating a card from a successor to a predecessor. However, it is still not as effective as an imperative decision.
EDIT : turned the first solution into an iterator block.
Ani
source share