views:

66

answers:

4

I have the class herichary as follows

CEntity---->CNode--->CElement

I have a

class Nodes : List<Cnode>

and

Class Elements : List<Element>

Node class contain common item common across different project Element class has item specific to a project.

I have to shallow copy the element list into the node list (basically down casting the elements to nodes)

+1  A: 

Supposing you are using .net 3.0 or greater, the following code creates a NEW list with the SAME elements downcasted to CNodes:

List<CNode> shallowCopyNodesList =  elements.Cast<CNode>().ToList();

Then (if not already present) you should create a constructor taking a List<CNode> in Nodes class and do:

var shallowCopyNodes = new Nodes(shallowCopyNodesList);
digEmAll
I had done nodes.addrange(elements.Cast<CNode>().ToList());Its working fine. Thanks
Mohit
+1  A: 

You could just do this:

List<CNode> nodes = new List<CNode>();
foreach (CElement element in elements) {
  nodes.Add(element);
}

Where elements is a List.

You don't need to worry about casting back to CNode, because CElement inherits from that. The important thing to note is that the elements in the nodes list (in the example above), are in fact instances of CElement. If you wanted CNode you'd probably have to create a new instance of CNode using a copy constructor:

public CNode(CNode instance)
{
  this.Property = instance.Property;
}

And add a new instance of CNode:

nodes.Add(new CNode(element));
Matthew Abbott
Contravariance is only on [interfaces](http://msdn.microsoft.com/en-us/library/dd233059.aspx), not on concrete classes (like List), so that part won't work.
R0MANARMY
@ROMANARMY: actually it works for interfaces and delegate types, but your point is still correct: It doesn't work for `List<T>`.
Brian Rasmussen
Good point! Removed
Matthew Abbott
@Brian Rasmussen: Fair enough, I was thinking just in the context of this answer.
R0MANARMY
A: 

You can use the Cast operator in LINQ.

var nodelist = elementList.Cast<CNode>()
                   .ToList();
Winston Smith
That doesn't create a new copy of the list, just an enumerable over the old collection. You need a call to `ToList` in there to make it work.
R0MANARMY
A: 

What I have done is

nodes.addrange(ElementList.ConvertAll(new Converter<Elements, CNode>(ConvertElementsToNode))));

and

public static CNode ConvertElementsToNode(Element ele)
    {
      return ((CNode) ele);
    } // ConvertElementsToNode

but will there be any performance/ memory issue in this approach.

Mohit