Trong MVC4, tôi đang cung cấp hộp Tìm kiếm cho người dùng để tìm kiếm bất kỳ giá trị nào trong Bảng. Vì vậy, tôi thực hiện Điều kiện Lọc Generic ở phía máy chủ trong C#Thực hiện Bộ lọc LINQ với Biểu thức
Cần giúp đỡ để kết hợp nhiều biểu thức để tạo thành biểu thức duy nhất
Expression<Func<T, bool>>
Ví dụ
Bảng Cột
MenuText, Tên vai trò (Role.Name mapping), Actio nName
Bây giờ Nếu người dùng nhập vào hộp tìm kiếm cho ABC, có thể nằm trong bất kỳ hàng nào trong cột được hiển thị, cần phải lọc.
Mẫu
public class Menu
{
public string MenuText {get;set;}
public Role Role {get;set;}
public string ActionName {get;set;}
}
public class Role
{
public string Name {get;set;}
}
Cho đến nay tôi đã thực hiện
/// <summary>
/// string[] properties property.Name (MenuText, ActionName), including deeper Mapping names such as (Role.Name)
/// </summary>
public static Expression<Func<T, bool>> FilterKey<T>(string filterText, params string[] properties)
{
ParameterExpression parameter = Expression.Parameter(typeof (T));
Expression[] propertyExpressions = properties.Select(
x => !string.IsNullOrEmpty(x) ? GetDeepPropertyExpression(parameter, x) : null).ToArray();
Expression<Func<T, bool>> predicate = PredicateBuilder.False<T>();
foreach (Expression expression in propertyExpressions)
{
var toLower = Expression.Call(expression, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));
var like = Expression.Call(toLower, typeof(string).GetMethod("Contains"), Expression.Constant(filterText.ToLower()));
//TODO: Combine expressions to form single Expression<Func<T, bool>> expression
}
return predicate;
}
/// <summary>
/// To Get Deeper Properties such as Role.Name Expressions
/// </summary>
private static Expression GetDeepPropertyExpression(Expression initialInstance, string property)
{
Expression result = null;
foreach (string propertyName in property.Split('.'))
{
Expression instance = result ?? initialInstance;
result = Expression.Property(instance, propertyName);
}
return result;
}
Bạn đã đặt câu hỏi gần giống hệt nhau 3 lần trong 24 giờ qua ... – leppie