Skip to main content
 首页 » 编程设计

c#之使用 Where 条件给出空值的列表集合过滤

2024年01月28日26grandyang

我正在使用 EDM 从数据库 View 表中获取值 以 IList 类型查询。

它正在提供一些元素集合。

从这个集合中,我是 tring 根据一列过滤数据,但不提供 过滤数据,即使数据是基于条件存在的 查询如下。

为了从数据库中获取数据//它是 获取一些数据集合。

IList<EFModel.EntityModel.vwGetActiveEmployee> activeEmployeelist = TimeOffService.GetActiveEmployees(); 

这里我想根据 Column IsManger(值 1 或 0)过滤数据 为此,我写了这样的

IList<EFModel.EntityModel.vwGetActiveEmployee> managerlist = activeEmployeelist.Where(p => p.IsManager == 1).Select(p => p) as IList<EFModel.EntityModel.vwGetActiveEmployee>; 

但是这里的经理列表显示空值。当我过滤数据时 在下面使用

 var emplistVar = activeEmployeelist.Where(p => p.IsManager.Equals(1)).Select(p => p); 

它显示了一些“var”类型的数据集合,但如果我给 类类型它显示为空。这是什么原因,这个数据是 取自数据库 View 数据。

请您参考如下方法:

此代码(重新格式化以避免滚动):

IList<EFModel.EntityModel.vwGetActiveEmployee> managerlist  
     = activeEmployeelist.Where(p => p.IsManager == 1) 
                         .Select(p => p) 
       as IList<EFModel.EntityModel.vwGetActiveEmployee>; 

...将总是将 managerlist 作为 null 给出,因为 Select 在我见过的任何实现中都不会返回 IList<T>。我怀疑你想要:

IList<vwGetActiveEmployee> managerlist = 
    activeEmployeelist.Where(p => p.IsManager == 1) 
                      .ToList(); 

请注意,除非您故意执行可能会有效失败的引用类型转换(在这种情况下,您通常应该根据 null 检查结果),否则您应该更喜欢强制转换而不是 as。如果您在此处使用了强制转换,您会立即看到异常,因为 Select 返回的值不是您期望的类型。