views:

227

answers:

2

What I want to do is pass IEnumerable to a method and have it return a copy of IEnumerable. However, I want each in the collection to be a copy, rather than just the collection being a copy.

An example:

// some random data from L2S
var data = (from p in sourceData
           select new
           {
               a = 1,
               b = "hello",
           }).ToArray();

var dataCopy = data.Copy(); // somehow i want 'dataCopy' to be a deep copy of 'data'

foreach (var d in dataCopy)
{
    // alter the item in the collection somehow
    d.b = d.b + "1";
}

// combine both sets of data
var finalData = data.Union(dataCopy);

So the collection 'finalData' has twice as many items as 'data' or 'dataCopy'. So all the 'b' parameters in 'dataCopy' have "1" appended to the end, but since they still reference the objects in 'data', all the 'b' parameters in 'data' ALSO have "1" appended to the end.

Since these are anonymous types, I can't simply 'clone' the object using the BinaryFormatter method, because the anonymous type isn't serializable. And I can't create a new from scratch using Activator.CreateInstance since the anonymous type doesn't have a parameterless constructor.

I realise that I could work around this by initially selecting my data into a class marked as Serializable, but I really don't want to have to modify that much code since each time i query the database, the parameters will be different...

Alternatively, could anyone recommend a replacement for the anonymous type? eg:

var data = (from p in sourceData
           select new SomeSortOfAnonymousTypeReplacement(new
           {
               a = 1,
               b = "hello",
           })).ToArray();

which would then implement a cloneable interface?

+1  A: 

This is fully (and very thoroughly!) answered at How do I create and access a new instance of an Anonymous Class passed as a parameter in C#?

Rex M
+1  A: 

I'm curious as to what value you think you will get out of cloning the anonymous type. In C#, all anonymous type's are shallowly immutable. They can be changed by mutating the values contained within the instance (such as adding a value to a collection). But even creating a shallow copy of the value via a clone won't prevent this side effect from being visible in existing instances.

The only value Clone could have on an anonymous type is if you deeply clone the value. That is clone both the anonymous type instance and all of it's internal values recursively. This is a very expensive operation and probably is not what you're looking for.

Can you give us more insight into what you are trying to accomplish? There may be an easier solution.

JaredPar