[英]Creating where condition for LINQ within switch statement
因此,基本上,我必須獲得4個不同角色的4個不同的員工列表。 List of Roles
是一個List of Enum
如下所示:
public enum Roles {
[Description("Level 1")]
L1,
[Description("Level 2")]
L2,
[Description("Level 3")]
L3,
[Description("Level 4")]
L4
};
L1
可以查看L1
, L2
, L3
和L4
L2
可以查看L2
, L3
和L4
L3
可以查看L3
和L4
。 L4
沒有查看任何員工的權限。 現在下面是我如何編寫查詢以獲取員工的信息。
if (!Equals(Role, Enum.GetName(typeof(GlobalMethods.Roles), 3)))
{
var _role = (GlobalMethods.Roles)Enum.Parse(typeof(GlobalMethods.Roles), Role,true);
List<EmployeeViewModel> employees = new List<EmployeeViewModel>();
switch (_role)
{
case GlobalMethods.Roles.L1:
employees = context.tblEmployees.Where(x => x.EmpID != homeViewModel.UserViewModel.EmpID).ToList().Select(x => new EmployeeViewModel
{
EmpActive = x.EmpActive,
EmpDOB = x.EmpDOB,
EmpName = x.EmpName
}).ToList();
break;
case GlobalMethods.Roles.L2:
employees= context.tblEmployees.Where(x => x.EmpID != homeViewModel.UserViewModel.EmpID).ToList().Where(x=>x.EmpRole != Enum.GetName(typeof(GlobalMethods.Roles), 0)).Select(x => new EmployeeViewModel
{
EmpActive = x.EmpActive,
EmpDOB = x.EmpDOB,
EmpName = x.EmpName,
}).ToList();
break;
case GlobalMethods.Roles.L3:
employees = context.tblEmployees.Where(x => x.EmpID != homeViewModel.UserViewModel.EmpID).ToList().Where(x.EmpRole != Enum.GetName(typeof(GlobalMethods.Roles), 0) && x.EmpRole != Enum.GetName(typeof(GlobalMethods.Roles), 1)).Select(x => new EmployeeViewModel
{
EmpActive = x.EmpActive,
EmpDOB = x.EmpDOB,
EmpName = x.EmpName,
}).ToList();
break;
default: break;
}
}
因此,在上面的代碼中,我具有相同的LINQ查詢,但是只有where
條件不同。 有什么方法可以准備動態where
條件並一次獲取列表?
這應該工作。 它假設每個GlobalMethods.Roles可以查看具有更大int值的所有角色。 您所指定的角色就是這種情況。
if (!Equals(Role, Enum.GetName(typeof(GlobalMethods.Roles), 3)))
{
var _role = (GlobalMethods.Roles)Enum.Parse(typeof(GlobalMethods.Roles), Role, true);
List<EmployeeViewModel> employees = new List<EmployeeViewModel>();
string[] viewableRoles = GetViewableRoles(_role);
employees = context.tblEmployees
.Where(x => x.EmpID != homeViewModel.UserViewModel.EmpID && viewableRoles.Contains(x.EmpRole))
.Select(x => new EmployeeViewModel
{
EmpActive = x.EmpActive,
EmpDOB = x.EmpDOB,
EmpName = x.EmpName
}).ToList();
}
private string[] GetViewableRoles(GlobalMethods.Roles userRole)
{
//Uncomment if L4 can actually view no roles, including itself.
// /if (userRole == GlobalMethods.Roles.L4)
// {
// return new string[0];
// }
IEnumerable<GlobalMethods.Roles> allRoles = Enum.GetValues(typeof(GlobalMethods.Roles)).Cast<GlobalMethods.Roles>();
return (from role in allRoles
where (int)role >= (int)userRole
select role.ToString()).ToArray();
}
這是簡化的,但是您可以執行以下操作:
class Program
{
static void Main(string[] args)
{
var list = new List<Person>
{
new Person{ Name = "John" },
new Person{ Name = "Amy" }
};
Func<Person, bool> pred = null;
Roles role = Roles.RoleA;
switch (role)
{
case Roles.RoleA:
pred = p => p.Name.StartsWith("J");
break;
case Roles.RoleB:
pred = p => p.Name.StartsWith("A") && p.Name.Length >= 3;
break;
default:
break;
}
var result = list.Where(pred);
}
}
class Person
{
public string Name { get; set; }
}
enum Roles
{
RoleA,
RoleB
}
以下是通用的表達式樹擴展方法,可以滿足以下要求(您當然需要進行修改以適合您的特定要求)
T
是IEnumerable
的最終類型 T1
是where子句中用於過濾的列的類型
在將Expression Tree to Func
編譯Expression Tree to Func
同時,聲明給定Type T
外部擴展方法的ParameterExpression
以便重用,盡管這也可以在Extension method
和Func
生成期間分別完成
ParameterExpression parameterType = Expression.Parameter(typeof(T), "object");
public static class CustomExpression { // Create Initial Expression Tree public static BinaryExpression InitialExpression<T,T1>( ParameterExpression parameterType string columnName, T1 value) { // Optional can be taken outside the Extension method to create a Func<T,bool> //ParameterExpression parameterType = Expression.Parameter(typeof(T), "object"); MemberExpression typeColumn = Expression.Property(parameterType, columnName); ConstantExpression constant = Expression.Constant(value, typeof(T1)); return Expression.NotEqual(typeColumn, constant); } // Create Combined Expression Tree public static BinaryExpression CombinedExpression<T,T1>(this BinaryExpression mainExpression, ParameterExpression parameterType string columnName, T1 value) { // Optional can be taken outside the Extension method to create a Func<T,bool> //ParameterExpression parameterType = Expression.Parameter(typeof(T), "object"); MemberExpression typeColumn = Expression.Property(parameterType, columnName); ConstantExpression constant = Expression.Constant(value, typeof(T1)); return Expression.And(mainExpression,Expression.NotEqual(typeColumn, constant)); } }
以下是您的情況下的呼叫層次結構:
為Linq
查詢聲明最終的二進制表達式:
BinaryExpression finalBinaryExpression = null;
switch (_role) { case GlobalMethods.Roles.L1: finalBinaryExpression = CustomExpression.InitialExpression<EmployeeViewModel,int> (parameterType,"EmpID",homeViewModel.UserViewModel.EmpID); break; case GlobalMethods.Roles.L2: finalBinaryExpression = CustomExpression.InitialExpression<EmployeeViewModel,int> (parameterType,"EmpID",homeViewModel.UserViewModel.EmpID) .CombinedExpression<EmployeeViewModel,Roles> (parameterType,"EmpRole",Enum.GetName(typeof(GlobalMethods.Roles), 0)); break; case GlobalMethods.Roles.L3: finalBinaryExpression = CustomExpression.InitialExpression<EmployeeViewModel,int> (parameterType,"EmpID",homeViewModel.UserViewModel.EmpID) .CombinedExpression<EmployeeViewModel,Roles> (parameterType,"EmpRole",Enum.GetName(typeof(GlobalMethods.Roles), 0)) .CombinedExpression<EmployeeViewModel,Roles> (parameterType,"EmpRole",Enum.GetName(typeof(GlobalMethods.Roles), 1)); break; }
通過如下編譯二進制表達式來創建一個genericFunc
Func<T, bool> filterFunc = Expression.Lambda<Func<T, bool>> (finalBinaryExpression, parameterType).Compile();
最終結果應用上面創建的Func
var finalResult = context.tblEmployees.Where(o => filterFunc(o));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.