I have found a work around for my issue, but I was wondering if someone can explain why this is happening.
I have a class DataCollector.
public class DataCollector
{
public string Name { get; set; }
public string Group { get; set; }
public int Count { get; set; }
public Brush Color { get; private set; }
public DataCollector(string name, string group, int count, Brush color)
{
Name = name;
Group = group;
Count = count;
Color = color;
}
}
In my code I have an ObservableCollection of DataCollector.
public ObservableCollection<DataCollector> dataGrid { get; set; }
I collect my data and use it just fine until when I went to add more features to the code.
I want to go through “dataGrid” and make a list of Groups and get a total count from all Names.
List<DataCollector> dataCollector = new List<DataCollector>();
List<string> _groupNames = new List<string>();
foreach (DataCollector dc in dataGrid)
{
int cnt = 0, index = 0;
bool groupFound = false;
if (dataCollector.Count == 0)
{
_groupNames.Add(dc.Group);
dataCollector.Add(dc));
}
else
{
foreach (string groupNames in _groupNames)
{
if (groupNames == dc.Group)
{
index = cnt;
nameFound = true;
}
cnt++;
}
if (nameFound)
{
// When I do this my dataGrid.Count increments, too
dataCollector[index].Count += dc.Count;
}
else
{
_groupNames.Add(dc.Group);
dataCollector.Add(dc);
}
}
}
To get around this I changed
dataCollector.Add(dc);
to
dataCollector.Add(new DataCollector(dc.Name, dc.Group, dc.Count, dc.Color));
Why did I have to this? Does adding “dc” to “dataCollector” create a link to “dataGrid”? If it does it doesn’t make sense.
You do that because
dataCollector.Add(dc)copies the reference to the memory location of an object. So changes to the data at the location is reflected in either collection as they hold pointers to the same objects.What you could do instead is to mimic a copy constructor.
It sorts of keep your code clean.