Joining two IEnumerable I'm trying to merge two nodes. Basically, the idea is to take all children in left and new ones in right. Is there any way to get rid of toAdd variable and do it in a clean way?

I don't want to convert any IEnumerable&lt;T&gt; to List or Array in this merge process.

public IEnumerable&lt;TChild&gt; NodeMerge&lt;TNode, TChild, TKey&gt;(TNode left, TNode right,
Func&lt;TNode, IEnumerable&lt;TChild&gt;&gt; getChildren, Func&lt;TChild, TKey&gt; getKey)
{
    var lChildren = getChildren(left);
    var rChildren = getChildren(right);

    IEnumerable&lt;TChild&gt;[] toAdd = new IEnumerable&lt;TChild&gt;[2];

    // Common Keys between left and right
    toAdd[0] = lChildren.Where(s =&gt; rChildren.Select(p =&gt; getKey(p)).Contains(getKey(s)));

    // new keys added to right
    toAdd[1] = rChildren.Where(s =&gt; lChildren.Select(p =&gt; getKey(p)).Contains(getKey(s)) == false);

    return toAdd.SelectMany(s =&gt; s);
}
Little cleaner:

// Common Keys between left and right
var result = lChildren.Where(s =&gt; rChildren.Select(p =&gt; getKey(p)).Contains(getKey(s))).ToList();

// new keys added to right
result.AddRange(rChildren.Where(s =&gt; lChildren.Select(p =&gt; getKey(p)).Contains(getKey(s)) == false));

return result;


Without ToList():

public static IEnumerable&lt;T&gt; Merge&lt;T&gt;(this IEnumerable&lt;T&gt; first, IEnumerable&lt;T&gt; second)
{
    foreach (var item in first)
        yield return item;

    foreach (var item in second)
        yield return item;
}


In your NodeMerge method:

return lChildren.Where(s =&gt; rChildren.Select(p =&gt; getKey(p)).Contains(getKey(s))).Merge(rChildren.Where(s =&gt; lChildren.Select(p =&gt; getKey(p)).Contains(getKey(s)) == false));