【问题标题】:Use of Contains inside a Select expression在 Select 表达式中使用 Contains
【发布时间】:2026-01-23 10:10:02
【问题描述】:

我想创建一个 CheckboxList 来检查用户的角色,并显示所有可用选项,用户界面没问题。但是下面的代码不起作用。

        var applicationUser = db.AspNetUsers.Include(x => x.AspNetRoles)
                              .FirstOrDefault(x => x.Id == id.Value);

        if (applicationUser == null)
        {
            return HttpNotFound();
        }


        var model = new ViewModels.UsuarioViewModel();

        model.Id = applicationUser.Id;
        model.UserName = applicationUser.UserName;
        model.Name = applicationUser.Name;
        model.Email = applicationUser.Email;
        model.EmailConfirmed = applicationUser.EmailConfirmed;
        model.PhoneNumber = applicationUser.PhoneNumber;
        model.PhoneNumberConfirmed = applicationUser.PhoneNumberConfirmed;
        model.Active = applicationUser.Active;


        model.RolesList = db.AspNetRoles.Select(r => new SelectListItem
                            {
                                Selected =
                               applicationUser.AspNetRoles.Contains(x => x.Id == r.Id),
                                Text = r.Name,
                                Value = r.Name
                            }).ToList();
        return View(model);

RolesList 是一个 IEnumerable SelectListItem

问题在于“selected = applicationUser.AspNetRoles.Contains(x => x.Id == r.Id)”部分。

编辑:

好的,现在我有一个工作代码:

model.RolesList = db.AspNetRoles.ToList().Select(r => new SelectListItem
                            {
                                Selected = (applicationUser.AspNetRoles.
                                           Where(x => x.Id == r.Id).ToList().Count > 0),
                                //Selected = false,
                                Text = r.Name,
                                Value = r.Name
                            });

我无法使用 Contains 使其工作。

我想知道是否可以在此表达式中使用 contains。 + Count 看起来不对的地方。

【问题讨论】:

  • 您自己分配的布尔值的结果是否正常?我的意思是,设置属性的问题还是表达式中的问题?发帖前先调试一下吧
  • @D.Petrov 表达式错误,我无法使用包含。它抛出编译错误的方式,调试不是一个选项。更改为“Selected = false”有效,并且在我可以使用 Where + Count 进行工作之后...还在 Select 之前添加一个 ToList() 以在列表中使用 linq。

标签: c# linq


【解决方案1】:

你不想要包含,你想要any

Selected = applicationUser.AspNetRoles.Any(x => x.Id == r.Id),

contains 查看给定元素是否在集合中,根本不是一回事,我很惊讶你的代码竟然编译了

【讨论】: