Tôi đang tạo một truy vấn LINQ động với mã này. Có vẻ như để làm việc, nhưng khi tôi có nhiều hơn một searchString trong tìm kiếm của tôi, (vì vậy khi nhiều biểu thức được thêm vào, tôi nhận được lỗi sau:Biểu thức LINQ. Biến 'p' của loại được tham chiếu từ phạm vi, nhưng nó không được xác định
Variable 'p' of type referenced from scope, but it is not defined**
Tôi đoán tôi chỉ có thể xác định/sử dụng p một lần. nhưng, nếu như vậy, tôi cần phải thay đổi mã của tôi một chút. Bất cứ ai có chỉ cho tôi đi đúng hướng ở đây?
if (searchStrings != null)
{
foreach (string searchString in searchStrings)
{
Expression<Func<Product, bool>> containsExpression = p => p.Name.Contains(searchString);
filterExpressions.Add(containsExpression);
}
}
Func<Expression, Expression, BinaryExpression>[] operators = new Func<Expression, Expression, BinaryExpression>[] { Expression.AndAlso };
Expression<Func<Product, bool>> filters = this.CombinePredicates<Product>(filterExpressions, operators);
IQueryable<Product> query = cachedProductList.AsQueryable().Where(filters);
query.Take(itemLimit).ToList(); << **error when the query executes**
public Expression<Func<T, bool>> CombinePredicates<T>(IList<Expression<Func<T, bool>>> predicateExpressions, Func<Expression, Expression, BinaryExpression> logicalFunction)
{
Expression<Func<T, bool>> filter = null;
if (predicateExpressions.Count > 0)
{
Expression<Func<T, bool>> firstPredicate = predicateExpressions[0];
Expression body = firstPredicate.Body;
for (int i = 1; i < predicateExpressions.Count; i++)
{
body = logicalFunction(body, predicateExpressions[i].Body);
}
filter = Expression.Lambda<Func<T, bool>>(body, firstPredicate.Parameters);
}
return filter;
}
Tôi không hiểu lắm. Dường như 'CombinePredicates' của bạn mong đợi các biểu thức' n' và 'n-1'. Tuy nhiên, tại nơi bạn gọi nó, bạn có một loạt các toán tử có độ dài '1'. Tôi sẽ mong đợi một ngoại lệ đi ra khỏi giới hạn của mảng nếu có nhiều hơn '2' predicates để tham gia. –
Tôi đã thấy rằng, tôi đã lấy ra một số công cụ để làm cho ví dụ của tôi nhỏ gọn hơn. Nhưng tôi sẽ thay đổi câu hỏi của tôi để làm cho phần đó về mặt kỹ thuật chính xác. – Tys
Tôi đã sửa phần đó.Nhưng vẫn còn vấn đề vẫn còn như nó được. – Tys