Search code examples
darthashmapnested-lists

Compare two nested lists and store difference in third list in Dart


I have two lists of salesOrderHeader (lets call them Before and After) and need to check if there is a difference on the salesQty field. If a difference is found it is recorded in a third list (lets call it Differences). Supposedly the items that need to be compared will be in the same index but to be prudent I'd like the salesId and itemRecId to match between the two lists before calculating the differences.

salesOrderhHeader.dart

class salesOrderHeader {
  String? salesId = "";
  List<SalesOrderLine>? salesOrderLine;

salesOrderLine.dart

class salesOrderLine {
  String salesId = "";
  int itemRecId = "";
  String itemId = "";
  String itemName = "";
  double salesQty = 0.0;

Solution

  • This is what I managed to do, seems to work but I want to know if there is a better answer.

    for (var i = 0; i < Before!.length; i++) { 
        for (var j = i; j < Before![i].salesOrderLine!.length; j++) { 
          for (var k = 0; k < After.length; k++) { 
            for (var l = k; l < After[i].salesOrderLine!.length; l++) { 
              if (Before![i].salesOrderLine![j].salesId == After![k].salesOrderLine![l].salesId && Before![i].salesOrderLine![j].itemRecId == After![k].salesOrderLine![l].itemRecId ){
                if (Before![i].salesOrderLine![j].salesQty != After![k].salesOrderLine![l].salesQty){             
    
                  double newQty = Before![i].salesOrderLine![j].salesQty - After![k].salesOrderLine![l].salesQty;
    
                  List<SalesOrderLine> Difference = [];
                  Difference.add(new SalesOrderLine(salesId: After![k].salesOrderLine![l].salesId,
                                                        itemRecId: After![k].salesOrderLine![l].itemRecId,
                                                        itemId: After![k].salesOrderLine![l].itemId,
                                                        itemName: After![k].salesOrderLine![l].itemName,
                                                        salesQty: newQty));
                  
                }
              }
            }
          }
        }
      }