• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 52343
  • Last Modified:

Questions Tags Users Badges Unanswered Ask Question

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.

 bWJwN.png

In anoter forum they helped me with this code


 var childrenByParentID = _unitDataSet.Unit.AsEnumerable().
                                     GroupBy(child => child.Field<int?>("ParentUnitId")).
                                     ToDictionary(group => group.Key);

            // Parents = children with no parent
            var parents = childrenByParentID[null];

            // 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 parent = parents.Single(parent => parent.Field<int>("UnitID") == group.Key);

                    var totalSurface = group.Sum(group => group.Field<int>("Surface"));
                    invalid = (totalSurface != parent.Field<int>("Surface"));
                }

                return invalid;
            });

            if (invalidGroup != null)
            {
                // .. do something special
            }

Open in new window


However I got this error.

 dlaxL.png
0
Simbios
Asked:
Simbios
1 Solution
 
guramritCommented:
There're some common mistakes in this code. You've to change it->

change
  var parent = parents.Single(parent => parent.Field<int>("UnitID") == group.Key);
to
  var parent = parents.Single(p => p.Field<int>("UnitID") == group.Key);

change
    var totalSurface = group.Sum(group => group.Field<int>("Surface"));
to
    var totalSurface = group.Sum(g => g.Field<int>("Surface"));

last thing, you cannot compare object of KeyValuePair<,> with null, because its a Structure (valuetype) returned by following code
   invalidGroup = childrenByParentID.FirstOrDefault ......

try using ToLookup instead of ToDictionary

0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now