简体   繁体   中英

get collection with where clause as collection in Linq

Here is my service method:

 public List<RelatedInvoiceData> GetRelatedInvoices(InvoiceSearch invoiceSearchFilters)
 {
   List<InvoiceInfoView> invoices = _wiseStepDbContext.InvoiceInfoView.Where(i => i.RecruiterCompanyId == _securityManager.CurrentRecruiterCompanyId).ToList();

   List<RelatedInvoiceData> relatedInvoiceViewCollection = GetRelatedInvoiceCollection(invoices);

   if (invoiceSearchFilters.CustomerId > 0)
   {
        relatedInvoiceViewCollection = relatedInvoiceViewCollection.Where(i => i.CustomerId == invoiceSearchFilters.CustomerId).ToList();
   }

   if (invoiceSearchFilters.VendorId > 0)
   {
        relatedInvoiceViewCollection = relatedInvoiceViewCollection.Where(i => i.VendorId == invoiceSearchFilters.VendorId).ToList();
   }

   return relatedInvoiceViewCollection;
}

here is my filterObject :

public class InvoiceSearch
    {
        public int[] CustomerId { get; set; }

        public int[] VendorId { get; set; }
    }

Previously I used where in linq for single customer Id now i want filter with multiple customerIds and multiple VendorIds.

Now I want to go with array of CustomerIds. How to write LINQ for Array in Where clause. Thanks for any help

If I understand correctly, you mean that i.CustomerId is now an array or List<> . If that's the case, then you can use the .Contains() method. Something like this should do what you want: relatedInvoiceViewCollection = relatedInvoiceViewCollection.Where(i => i.CustomerId.Contains(invoiceSearchFilters.CustomerId)).ToList();

Edit: This question may be helpful if you want to check for intersections in two arrays, which you can do in your case like this: relatedInvoiceViewCollection = relatedInvoiceViewCollection.Where(i => i.CustomerId.Intersect(invoiceSearchFilters.CustomerId).Any()).ToList();

relatedInvoiceViewCollection.Where(x => relatedInvoiceViewCollection.Contains(invoiceSearchFilters.CustomerId)).ToList(); 

或者

relatedInvoiceViewCollection.Where(x => x.Contains(invoiceSearchFilters.CustomerId)).ToList(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM