Reputation: 6790
I have a collection of nodes and each node could have a parent node. If the parent node exists I would like to insert it as a child (ie: the parent would become its own child) but I'm struggling to figure out a way to do this with linq if possible.
My non linq attempt:
private IList<IPageNode> addParentNode(IList<IPageNode> nodes) {
if (nodes[0].parent == null) return nodes;
var parentWithoutChildren = new PageNode {
name = nodes[0].parent.name,
isNavigable = nodes[0].parent.isNavigable,
url = nodes[0].parent.url,
children = null,
parent = null
};
nodes.Insert(0, parentWithoutChildren);
return nodes;
}
What I have so far works but there are two issue:
Upvotes: 1
Views: 148
Reputation: 19020
Well, the question is: Do you want to return a different list containing the same objects (and possibly an additional one) or do you want to return a new list of new objects?
Assuming the former:
public static IEnumerable<IPageNode> WithClonedParent(this IList<IPageNode> list)
{
var newParent = list.First().CloneParentIfSet();
if (newParent)
{
yield return newParent;
}
foreach (var node in list)
{
yield return node;
}
}
CloneParentIfSet
could be an extension method for IPageNode
which does what you currently do in your new PageNode
statement.
Then you can use it like this: nodes.WithClonedParent()
which will be a new collection.
Not necessarily more efficient but maybe a bit more elegant (IMHO).
Upvotes: 2