I have the following datatable, which has Units information. The Units have a surface in 开发者_运维技巧square meters. However the units can be split into subunits, in the datatable there is a ParentUnitID to know if that unit is splitted or not.
I need to validate that the sum of the surface of the child units, is equal to the surface of the parent unit.
The current code is something like:
private void ValidateUnitsStep(WorkspaceCancelEventArgs e)
{
//Get data from step
GetUnitsData();
UserControlUnits Units = GetSmartPartByType<UserControlUnits>();
if (_unitDataSet.Unit.HasErrors)
{
e.Cancel = true;
}
DataRow[] rows = _unitDataSet.Unit.Select("ParentUnitId !=" + string.Empty);
foreach(DataRow dr in rows)
{
}
}
I would like to do this with LINQ.
Edit: Yes, thats also possible, up to 2 levels of childs only
Unit A (100 sqm)
-UnitA1 (70)
-UnitA11 (20)
-UnitA12 (20)
-UnitA12 (30)
-UnitA2 (30)
-UnitA21 (20)
-UnitA22 (10)
A possible implementation using linq to DataSet
(1 level of children, but I'm sure you can work out for 2 levels)
// Group the records by parent ID (potentially null)
var childrenByParentID = _unitDataSet.Unit.AsEnumerable().
ToLookup(child => child.Field<int?>("ParentUnitId"));
// Parents = children with no parent
var parentsByID = childrenByParentID[null].ToLookup(parent => parent.Field<int>("UnitID"));
// Look for the first group which sum of surfaces is not the same as the parent's surface
var invalidGroup = childrenByParentID.FirstOrDefault(group =>
{
bool invalid = false;
if (group.Key != null)
{
// Not the parents group
var currentParent = parentsByID[group.Key]);
var totalSurface = group.Sum(row => row.Field<int>("Surface"));
invalid = (totalSurface != currentParent.Field<int>("Surface"));
}
return invalid;
});
if (invalidGroup != null)
{
// .. do something special
}
精彩评论