It sounds like detail
is a reference type. When you duplicate the list, each list (whose backing store is an array) contains references to the same set of detail
instances.
You need to make a deep copy or clone.
If detail
implements ICloneable
it's easy:
List<detail> original = GetListOfDetails() ;
List<detail> clone = original.Select( x => x.Clone() ).Cast<detail>().ToList() ;
However, you're at the mercy of the semantics of detail.Clone()
: there's no guarantee that it, actually performs a deep copy. See MemberwiseClone()
for some suggestions on how you might implement a correct deep copy.
If detail
is serializable, that is, the class has the attribute [Serializable]
or it implements ISerializable
, the easiest and simplest (though neither elegant nor particular fast) way would be to serialize it to a stream and rehydrate it as a new list, something like this:
public static IEnumerable<T> Clone<T>( this IEnumerable<T> list )
{
BinaryFormatter serializer = new BinaryFormatter() ;
using ( MemoryStream stream = new MemoryStream() )
{
foreach( T item in list )
{
// serialize
serializer.Serialize(stream,item) ;
stream.Flush() ; // probably unneeded for a memory stream, but belts-and-suspenders, right?
// rewind and rehydrate
stream.Seek(0,SeekOrigin.Begin) ;
T clone = (T) serializer.Deserialize( stream ) ;
// rewind and clear the memory stream
stream.Seek(0,SeekOrigin.Begin) ;
stream.SetLength(0) ;
yield return clone ;
}
}
}
...
List<detail> original = GetListOfDetails() ;
List<detail> clone = original.Clone().ToList() ;