Home > Mobile >  Filter a list within a list using linq in C#
Filter a list within a list using linq in C#

Time:04-20

I want to filter a list that is inside a list in C# using Linq

 var  catalogs = await _context.MerchantCatalogs
            .Include(x => x.merchantDiscounts)
            .ToListAsync();

I have a list of items inside the item there is a list of discounts and I need to get the discount for the specific user

MerchantCatalogs has a field called discount which has a discount type either (1,2) and I need to only get the discount within the list which has a type of 2

public class MerchantCatalogs
{
    int ID;
    public ICollection<MerchantDiscount> merchantDiscounts { get; set; }
}
public class MerchantDiscount
{
    int id;
    int type;
}

how do I get the list which has an inner list of MerchantDiscount = 1

CodePudding user response:

Try the Where clausule to filter the results:

var  catalogs = await _context.MerchantCatalogs
        .Include(x => x.merchantDiscounts.Where(discount => discount.type == 2))
        .ToListAsync();

And if you only want the Merchants that HAVE any discount of type 2

var  catalogs = await _context.MerchantCatalogs
        .Include(x => x.merchantDiscounts.Where(discount => discount.type == 2))
        .Where(merchant=> merchant.merchantDiscounts.Any())
        .ToListAsync();
  • Related