bflemi3
bflemi3

Reputation: 6790

Create collection that includes itself

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:

  1. It's not with linq and I'm assuming that linq would be the most efficient/effective way to accomplish this.
  2. The object that's passed in is being manipulated, changed and returned and I can't have that happen. I know I could just create a new object and return that but I'd like to learn something new if it's possible.

Upvotes: 1

Views: 148

Answers (1)

ChrisWue
ChrisWue

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

Related Questions