How to apply filter in child tables using Linq

Net application. I have one entity with child entities. I have to filter based on child entity values. For example in the below query,

 var sourceProposal = proposals.ProposalResults.Where(x => x.Quotes.All(c => c.QuotationId.ToLower().Trim() == sourceQuoteId.ToLower().Trim()));

I have input parameter sourceQuoteId which is present in child table quotes. Here parent table is Proposal. So there will be multiple proposal and each proposal has multiple quotes. Idea is to filter proposal based on the quote id. Above query works fine whenever only one quote exists but it will not filter when there are multiple quotes. Can someone help me to filter based on child table?

3 answers

  • answered 2022-05-06 09:40 John

    It seems that you should be calling Any rather than All, if what you want is proposals with any quote that satisfies the criterion.

  • answered 2022-05-06 09:44 Armando Bracho

    The reason you are getting this working only when 1 result is in the collection is because you are using an All operator, All operator is used to check whether all elements in a sequence satisfy given condition or not.

    What you want to use is the Any operator, Any operator is used to check whether any single element in a sequence satisfy a given condition or not.

    Your query should then be:

        var sourceProposal = proposals.ProposalResults
           .Where(x => x.Quotes.Any(c => c.QuotationId.ToLower().Trim() == sourceQuoteId.ToLower().Trim()));

  • answered 2022-05-06 09:48 MD. RAKIB HASAN

    try this:

    var sourceProposal = proposals.ProposalResults.Where(x => x.Quotes.Any(c => c.QuotationId.ToLower().Trim() == sourceQuoteId.ToLower().Trim()));

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum