Home > Enterprise >  How to retrieve object by comparing nested object value to another object value
How to retrieve object by comparing nested object value to another object value

Time:05-17

I have Object A which has a field DocumentName and another object nested inside it called Object B which has a field called Sku. I Have a List<ObjectA> and List<ObjectB> I need to now compare ObjectA.ObjectB.Sku to ObjectB.Sku to retrieve The corresponding Object A. How would I go about doing this in C#? I have tried the following but it does not work:

foreach (var item in blockProducts)
            {
                foreach (var block in flyerBlocks)
                {
                    CurrentBlock = (FlyerBlock)block.Products.Where(x => x.Sku.Equals(item.Sku));
                  

                }
}

blockProducts represents ListObjectB while flyerBlocks represents ListObjectA. Any help would be appreciated

CodePudding user response:

Please have a look at the documentation. Equals evaluates whether or not you have one instance. If you want to compare two instances for equality based on the state of the instances you can override Equals.

CodePudding user response:

So I figured out what I was doing wrong. This is how I solved my issue I did not need the second foreach.

foreach (var item in blockProducts)
{
     var CurrentBlock = flyerBlocks
                    .FirstOrDefault(
                    b => b.Products.Any(p => p.Sku == item.Sku)
                   );            
}
  • Related