0

I am passing in an array of objects which I want UNTOUCHED but for some reason no matter what I try the original array passed in is being changed.

private DSPPositionPeriodDO[] CompactShortTermData(DSPPositionPeriodDO[] data)
{
    DSPPositionPeriodDO[] resultArray = (DSPPositionPeriodDO[])data.Clone();
    int? hoursToAggBy = null;
    // it is short term, the data gets too much so decide how many
    // hours to aggregate by.
    var days = (_endDate - _startDate).TotalDays;
    if (days <= 3)
        hoursToAggBy = null;
    else if (days > 3 && days <= 7)
        hoursToAggBy = 1;
    else if (days > 7 && days <= 14)
        hoursToAggBy = 2;
    else if (days > 14 && days <= 21)
        hoursToAggBy = 3;
    else if (days > 21)
        hoursToAggBy = 4;

    if (hoursToAggBy != null)
    {
        // round down hours
        foreach (var posPeriod in resultArray)
        {
            var sl = posPeriod.StartLocal;
            sl = sl.AddHours(-(sl.Hour % hoursToAggBy.Value));
            sl = sl.AddMinutes(-sl.Minute);
            posPeriod.StartLocal = sl;
        }

        // group by entity & time -- get average
        var groupedData = resultArray.GroupBy(x => new
        {
            x.EntityId,
            x.EntityCode,
            x.StartLocal
        })
        .Select(g => new DSPPositionPeriodDO
        {
            EntityId = g.Key.EntityId,
            EntityCode = g.Key.EntityCode,
            StartLocal = g.Key.StartLocal,
            Volume = g.Average(v => v.Volume),
            AverageVolume = null
        });

        resultArray = groupedData.ToArray();
    }
}

I have tried to create a seperate copy like :

var x = original.ToArray()

toList()

Clone()

etc.

By original I mean the data object being passed in. I wish it not to be changed at all.

AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
sprocket12
  • 5,368
  • 18
  • 64
  • 133
  • [Clone](http://msdn.microsoft.com/en-us/library/system.array.copy.aspx) in array performs shallow copy, i.e. it doesn't create a copy of objects itself – Ilya Ivanov Jun 21 '13 at 11:42
  • If you don't want that to happen then either the objects in the array must be value types or you must deep clone them manually. – Jon Jun 21 '13 at 11:43

1 Answers1

1

From Array.Clone:

The references in the new Array point to the same objects that the references in the original Array point to.

You need to clone each object into the new array.

Oded
  • 489,969
  • 99
  • 883
  • 1,009