[英]Complex linq query to validate sum of child units using the same datatable
我有以下數據表,其中包含單位信息。 單位的面積為平方米。 但是,可以將單位拆分為子單位,在數據表中有一個ParentUnitID可以知道該單位是否被拆分。
我需要驗證子單元表面的總和等於父單元表面的總和。
當前代碼如下:
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)
{
}
}
我想用LINQ做到這一點。
編輯:是的,那也是可能的,最多只有兩個級別的孩子
A室(100平方米)
-UnitA1(70)
-UnitA11 (20)
-UnitA12 (20)
-UnitA12 (30)
-UnitA2(30)
-UnitA21 (20)
-UnitA22 (10)
使用linq到DataSet的可能實現
(1個等級的孩子,但我敢肯定您可以解決2個等級的問題)
// 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.