【问题标题】:IN query using LINQ for IEnumerable List of items使用 LINQ 查询 IEnumerable 项目列表
【发布时间】:2016-07-27 15:24:33
【问题描述】:

努力做到这一点。 所以我有一个模型视图,它有 Ienumerable BusinessUnits 来为视图绑定 ListBox 多选,我有 Ienumerable selectedBusinessUnit 来保存选定的值。 一旦选择了多个值并回发到控制器,我就会努力使用 linq 查询来检查数据库中的值是否与 IEnumberable 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 })

// 控制器

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 是项目表(项目对象)中的列之一(如果您愿意,可以选择属性),以防有人想知道。 所以最终结果我正在寻找获得收入组织IN选择的业务单位列表

的项目列表

【问题讨论】:

  • result = result.Where(x =&gt; x.Project.Revenue_Organization.Contains(projectsSearchViewModel.selectedBusinessUnit));projectsSearchViewModel.selectedBusinessUnit 是 IEnumerable 你不能使用 contains。将语句更改为result = result.Where(x =&gt; x.Project.Revenue_Organization.Contains(projectsSearchViewModel.selectedBusinessUnit.FirstOrDefault()));
  • Revenue_Organization 属性的类型是什么?
  • @shyu 属性是字符串

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您在错误的对象上使用了 Contains。反之亦然:

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

    我有这样的假设:

    projectsSearchViewModel.selectedBusinessUnit 是一个 IEnumerable。 x.Project.Revenue_Organization 是一个字符串值(数据库中要进行“IN”查询的列)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      相关资源
      最近更新 更多