[英]How to create dynamic Multiple And linq conditions in foreach loop
if (rowCount == 1)
{
query =
(from x in partJoinTableRepository.GetPartJoinQuery()
join y in partRepository.GetPartsQuery() on x.PartId equals y.Id
join z in partProductTypeReposiotry.GetPartProductTypesQuery() on x.PartId equals z.PartId
where y.IsSkipped == 0 && (y.IsDisabled != "Y" || y.IsDisabled == null) && z.CreatedDate == x.CreatedDate
&& x.CreatedDate == Convert.ToDateTime(fromDate) && cpaclassids.Contains(x.ProductTypeId.ToString())
select x).Cast<PartJoinTable>().AsQueryable();
predicate = PredicateBuilder.True(query);
}
else
{
query = query.Join(partJoinTableRepository.GetPartJoinQuery(), "PartID", "PartID", "inner", "row1", null).Cast<PartJoinTable>().AsQueryable();
// predicate = PredicateBuilder.True(query);
} //query contains multiple dynamic inner joins
//repids contains the list ,I used the predicate builder for the linq to create AND Queries
foreach(var item in repids)
{
predicate = PredicateBuilder.True(query);
if (typeid == "3")
{
predicate = predicate.And(z => ids.Contains(z.ProductTypeId.ToString()) &&
z.CreatedDate == Convert.ToDateTime(fromDate));
}
}
var count = query.Where(predicate).Distinct().Count();
上一行需要很長時間才能執行,ids包含列表,而查詢包含linq query。基本上,我需要形成多個“ AND”條件
//查詢需要花費大量時間來執行,並且多個和條件不起作用
如果我理解正確,那么您的問題是此查詢的運行時間很長。 讓我們在最后一行中查看代碼:
var count = query.Where(predicate).Distinct().ToList().Count();
在LINQ to SQL(和實體)中,如果您使用ToList()
, ToArray()
等,則不會執行查詢。例如,考慮以下查詢:
var strings = Db.Table
.Where((string s) => s.Contains("A")) // Will convert to something like WHERE s LIKE '%A%'
.Select(s => s.ToUpper()) // Will convert to something like SELECT upper(s)
.ToList(); // Here the query sends to the DB and executes
最終查詢為SELECT upper(s) FROM [Table] WHERE s LIKE '%A%'
所在的SELECT upper(s) FROM [Table] WHERE s LIKE '%A%'
。
在這種情況下,首先將查詢發送到數據庫,並獲取與條件相對應的所有對象( .Where()
) , 然后 在應用程序中獲取它們的計數。
相反,如果僅從數據庫中獲取計數,則查詢會更快:
var count = query.Where(predicate).Distinct().Count(); // No .ToList()! Here, .Count() executes the query.
刪除ToList
以提高性能。 因為ToList
執行查詢並檢索對象列表到內存。 但是您只需要數。 您不需要物體。
var count = query.Where(predicate).Distinct().Count();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.