c# - IN 查询使用 LINQ 查询 IEnumerable 项目列表

标签 c# asp.net asp.net-mvc linq

努力做到这一点。

所以我有一个模型 View ,它有一个 IEnumerable<selectlistitem> BusinessUnits为 View 绑定(bind)一个带有多选的列表框,我有 IEnumerable<string> selectedBusinessUnit保存选定的值。

一旦选择了多个值并将其回发到 Controller ,我就很难使用 linq 查询来根据 IEnumerable<string> selectedBusinessUnit 检查数据库中的值。 .更像是 SQL“IN”查询。

这是我的代码:

public class ProjectsSearchViewModel
{
        public IEnumerable<string> selectedBusinessUnit { get; set; }  //Selected Revenue Organization (Business Unit)
        [Display(Name = "Business Unit")]
        public IEnumerable<SelectListItem> BusinessUnits { get; set; } //populate list of business units from database for the listbox
    }

//我的看法

@Html.LabelFor(m => m.BusinessUnits, new { @class = "col-md-4 control-label" })
@Html.ListBoxFor(m => m.selectedBusinessUnit, Model.BusinessUnits, new { @class = "form-control", type = "dropdownlist", size = 5 })

// Controller

if (projectsSearchViewModel.selectedBusinessUnit != null)
                {                
                    result = result.Where(x => x.Project.Revenue_Organization.Contains(projectsSearchViewModel.selectedBusinessUnit));}

它说不能将 IEnumerable 转换为字符串

有没有人成功地做到了这样的事情。如果是这样,我很想知道怎么做。

更多代码

 var results = (from project in db.Projects
         join emp in db.Employees
         on project.Project_Manager equals emp.Employee_ID
         select new ProjectsList
         {
             Project = project,
             Employee = emp
         });

如果有人想知道,Revenue_organization 是项目表(项目对象)中的列之一(属性,如果你喜欢的话)。 所以最终结果我正在寻找 revenue_organization IN 选择的业务单位列表

的项目列表

最佳答案

假设 Project.Revenue_Organization 是一个字符串,您需要反转该语句。该集合应包含该字符串,但正如您所写的那样,它会检查该字符串是否包含该集合(这没有意义)。

result = result.Where(x => projectsSearchViewModel.selectedBusinessUnit.Contains(x.Project.Revenue_Organization));}

关于c# - IN 查询使用 LINQ 查询 IEnumerable 项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617245/

相关文章:

c# - SQL 2008 - INFORMATION_SCHEMA View 中的外键约束

asp.net - 使用 onkeypress 时 window.location.href 在 Safari 中不起作用

c# - 使用自定义事件刷新 ASP.NET 页面

Dynamics CRM 2011 Outlook 客户端中的 JavaScript 弹出窗口

c# - .csproj 文件无法正确导入其他项目

c# - 修复 global.asax 中的语法错误

c# - 简单生成的 MSIL 抛出 "Operation could destabilize the runtime"

asp.net - RaisePostBackEvent在错误的控件上被调用

.net - Asp.Net MVC 3 部分页面输出缓存不支持配置设置

c# - Razor:如果模型是 List<>,则 @Html.LabelFor 创建空的 "for"字段