在Linq中使用where子句作为集合获取集合

时间:2016-03-28 17:07:19

标签: c# linq where-clause

这是我的服务方法:

 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;
}

这是我的filterObject:

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

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

以前我在linq用于单个客户ID的地方现在我希望过滤多个customerIds和多个VendorIds。

现在我想使用CustomerIds数组。如何在Where子句中编写LINQ for Array。谢谢你的帮助

2 个答案:

答案 0 :(得分:2)

如果我理解正确,您的意思是i.CustomerId现在是数组或List<>。如果是这种情况,那么您可以使用.Contains()方法。这样的事情可以做你想做的事:relatedInvoiceViewCollection = relatedInvoiceViewCollection.Where(i => i.CustomerId.Contains(invoiceSearchFilters.CustomerId)).ToList();

修改: This question如果您想检查两个阵列中的intersections可能会有所帮助,您可以在这种情况下执行此操作:relatedInvoiceViewCollection = relatedInvoiceViewCollection.Where(i => i.CustomerId.Intersect(invoiceSearchFilters.CustomerId).Any()).ToList();

答案 1 :(得分:0)

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

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