Home > Back-end >  Lambda match condition in an attribute OR a sublist attribute of an object
Lambda match condition in an attribute OR a sublist attribute of an object

Time:10-14

Hello I have the following lambda to get purchases that match certain conditions:

select = this.Model
    .Where(a => DateTime.Now.Subtract(a.CreateDate).TotalDays <= range)
    .Where(i => i.PayDate != DateTime.MinValue)
    .Where(x => x.Product.Equals(product) 
             || x.Items.Any(y => y.Type.Equals(product)));

The part that is giving me trouble is this one (as it works without it):

 || x.Items.Any(y => y.Type.Equals(product))

Inside a purchase I got a sublist of added products that are related to the main product, as I want to check the prices of those subitems I have to get in the result everything related to the actual product.

-Model(list)
   -Purchase(object)
       Product(ProductType)
       Price(float)
      -Items(list)
         -PurchaseItem(object)
             Type(ProductType)
             Price(float)
   -purc...

What am I doing wrong?

CodePudding user response:

I think the reason is x.Product.Equals(product) always true for your data.

That means x.Items.Any(y => y.Type.Equals(product)) never execute.

CodePudding user response:

To use .Equals() and other extension methods @ linq to compare objects (product in your case), you should implement the IEquatable interface on the product class.

This forces you to implement:

bool Equals(T x, T y);
int GetHashCode(T obj);

IEquatable is for an object of type T so that it can compare itself to another of the same type.

Why not compare the productId?

.Where(x => x.Product.Id == product.Id)
  • Related