I do know that changing collection while you are enumeration within it will cause collection was modified exception
.
But if I get a subcollection from larger one, and while I'm enumerating that subcolletion I remove some item from larger one I still get this error. Invoking ToList
on subcollection solves this issue. But why it occurs?
var localCollection = someData.ToList(); // from DB Context
var localGrouped = localCollection.GroupBy(x => x.Id).Select(g => new { Id = g.Key, List = g.Select(x => x.Value) }); or .ToList(); // Here how I solve exception
var groups = new List<List<Int64>>();
while (localGrouped.Any())
{
var newSelected = new List<Int64>();
var firstGroup = localGrouped.First();
newSelected.Add(firstGroup.Id);
localGrouped.Remove(firstGroup);
var similiarGroups = localGrouped.Where(x => x.List.Intersect(firstGroup.List).Any()).ToList();
if (similiarGroups.Any())
{
foreach (var similiarGroup in similiarGroups)
{
//Changing something here in parent collection causes exception
newSelected.Add(similiarGroup.Id);
localGrouped.Remove(similiarGroup);
}
}
groupsOfParcels.Add(newSelected);
}