如何设置条件C#if语句和LINQ where语句?

时间:2018-12-05 16:52:05

标签: c# asp.net-mvc linq

我的情况的详细信息:如果用户有权查看某个位置的项目,则我需要查询以选择具有与用户所拥有的权限相匹配的工具的项目。用户可能具有对多个设施的权限。可能有一个用户有权访问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");
}

3 个答案:

答案 0 :(得分:4)

因此,您只需构造一个允许的设施列表,然后检查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));

要进一步简化它,您可以在某种地图中对角色和设施进行分组,然后进行迭代-例如,它将使添加新设施变得更加容易。

答案 1 :(得分:1)

您可以使用字典将其重构以将用户角色映射到设施:

var userFacilityMapping = new Dictionary<string, string>
{
    ["App_Inventory_LOC1_Access"] = "LOC1",
    ["App_Inventory_LOC2_Access"] = "LOC2",
    ["App_Inventory_LOC3_Access"] = "LOC3",
};
var userFacilities = userFacilityMapping
    .Where(x => HttpContext.Current.User.IsInRole(x.Key))
    .Select(x => x.Value)
    .ToArray();

items = items.Where(x => userFacilities.Contains(x.Facility));

答案 2 :(得分:1)

我认为您正在覆盖结果集。假设您有权访问LOC1和LOC3,它将首先选择所有LOC1项目,然后从LOC1项目中选择将为空的LOC3项目。

您只想过滤原始项目集。像

var results = new List<Item>();

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

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

if(System.Web.HttpContext.Current.User.IsInRole("App_Inventory_LOC3_Access")) 
{
    results.AddRange(items.Where(s => s.Facility == "LOC3"));
}
相关问题