'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?
Solution 1:[1]
It seems that you should be calling Any
rather than All
, if what you want is proposals with any quote that satisfies the criterion.
Solution 2:[2]
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()));
Solution 3:[3]
try this:
var sourceProposal = proposals.ProposalResults.Where(x => x.Quotes.Any(c => c.QuotationId.ToLower().Trim() == sourceQuoteId.ToLower().Trim()));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | John |
Solution 2 | Armando Bracho |
Solution 3 | MD. RAKIB HASAN |