首页 > 解决方案 > 如何设置条件 C# if 语句和 LINQ where 语句?

问题描述

我的情况的详细信息:如果用户有权查看某个位置的项目,我需要查询来选择具有与用户拥有的权限相匹配的设施的项目。一个用户可能拥有多个设施的权限。可能有一个用户可以访问 LOC1、LOC2 和 LOC3。可能有一个用户只能访问 LOC1。我可能忽略了一些非常简单的方法来解决这个问题。

if(System.Web.HttpContext.Current.User.IsInRole("App_Inventory_LOC1_Access")) 
{
    items = items.Where(s => s.Facility == "LOC1");
}

if(System.Web.HttpContext.Current.User.IsInRole("App_Inventory_LOC2_Access")) 
{
    items = items.Where(s => s.Facility == "LOC2");
}

if(System.Web.HttpContext.Current.User.IsInRole("App_Inventory_LOC3_Access")) 
{
    items = items.Where(s => s.Facility == "LOC3");
}

标签: c#asp.net-mvclinq

解决方案


因此,您只需构建一个允许的设施列表,然后检查是否s.Facility在这些设施中:

var facilities = new List<string>();
if(System.Web.HttpContext.Current.User.IsInRole("App_Inventory_LOC1_Access")) 
{
    facilities.Add("LOC1");
}
// same for other facilities
// ...

items = items.Where(s => facilities.Contains(s.Facility));

为了进一步简化它,您可以在某种地图中对角色和设施进行分组,并对其进行迭代——这将使添加新设施变得更加容易。


推荐阅读