开发者

Complex linq query to validate sum of child units using the same datatable

开发者 https://www.devze.com 2023-04-04 15:33 出处:网络
I have the following datatable, which has Units information.The Units have a surface in 开发者_运维技巧square meters.

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.

Complex linq query to validate sum of child units using the same datatable

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.

Complex linq query to validate sum of child units using the same datatable

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号