Home > Back-end >  C# filter list, All or with given value
C# filter list, All or with given value

Time:03-01

In my list, each list item consist of 2 properties ProductCategory ProductId

In my items there is not 0 valued neither ProductId nor ProductCategory

If client sends me as ProductId = 0 Product Category = 0

So must return all items in the list

If client sends me as ProductId = 2 ProductCategory = 0 I must return Only 2 id product in all of the ProductCategory

Or

ProductId=0
ProductCategory=2
I must return all of the products in 2 id ProductCategory..

Or ProductId=3 ProductCategory=2

 Return productId = 2 in product category 2

How can implement this code without using if else blocks? I have achieved this with 4 if/else blocks but I want to learn is there any better way

CodePudding user response:

You can achieve with the .Where statement as below:

Conditions:

  1. Match productId with 0 or product.ProductId equals to productId.
  2. Match productCategory with 0 or product.ProductCategory equals to productCategory.
  3. Must fulfill both conditions 1 & 2.
var products = PRODUCT_LIST
    .Where(x => (productId == 0 || x.ProductId == productId)
        && (productCategory == 0 || x.ProductCategory == productCategory))
    .ToList();
  • Related