Mihir Patel Mihir Patel - 9 months ago 27
C# Question

C# How do I compare two lists without sorting?

I need to compare gammaFactorWeigths and gammaFactors and make sure they must have the same number of factors and must be in the same order in both inputs (guidance, planning, and goal).

I deserialized the input below. So I have a list of portfolios and a list of phases. I need to compare gammaFactor from portfolios and gammaFactorWeigths in phases which is a List of Lists. Can someone assist me how to do this? I would prefer a solution without lambdas.

public class AlphaCalcParam
{
public List<PortfolioInputModel> portfolios { get; set; }
public List<PhaseInputModel> phases { get; set; }

public bool Validation(ref string errString)
{

errString = "";
return true;

// check if gammaFactor and gammaFactorWeights match are in the same order
}
}


Data Structure below:

{
"portfolios":[
{
"identifier": "id 1",
"gammaFactors":[
{
"factorIdentifier":"Guidance",
"factorOffered":1
},
{
"factorIdentifier":"Planning",
"factorOffered":0
},
{
"factorIdentifier":"Goal",
"factorOffered":0
}
]
},
{
"identifier": "id 2",
"gammaFactors":[
{
"factorIdentifier":"Guidance",
"factorOffered":1
},
{
"factorIdentifier":"Planning",
"factorOffered":1
},
{
"factorIdentifier":"Goal",
"factorOffered":1
}
]
}
],
"phases":[
{

"identifier": "xyz",
"gammaFactorWeights":[
{
"factorIdentifier":"Guidance",
"factorWeight":0.0075
},
{
"factorIdentifier":"Planning",
"factorWeight":0.003
},
{
"factorIdentifier":"Goal",
"factorWeight":0.0015
}
]
},
{
"identifier": "xyz",
"gammaFactorWeights":[
{
"factorIdentifier":"Guidance",
"factorWeight":0.005
},
{
"factorIdentifier":"Planning",
"factorWeight":0.0025
},
{
"factorIdentifier":"Goal",
"factorWeight":0.0015
}
]
},
{
"identifier": "xyz",
"gammaFactorWeights":[
{
"factorIdentifier":"Guidance",
"factorWeight":0.0025
},
{
"factorIdentifier":"Planning",
"factorWeight":0.002
},
{
"factorIdentifier":"Goal",
"factorWeight":0.0015
}
]
}
]
}

Answer Source

Here is an approach I am thinking of.

int length = Math.Min(portfolios.Count, phases.Count); // Only if collections can be of different length
for (int i = 0; i < length; i++)
{
     var portfolio = portfolios[i];
     var phase = phases[i];

     var factors = portfolio.gammaFactors;
     var weights = phase.gammaFactorWeights;

     var factorOffered = int.MaxValue;

     for (int j = 0; j < factors.Count; j++)
     {
          if (factors[j].factorOffered > factorOffered)
          {
              // Next factor is greater than current which fails validation.
              return false;
          }
          factorOffered = factors[j].factorOffered;
     }

     // Same can be done for weights.
}