在Select表达式中使用Contains

时间:2016-06-30 15:10:06

标签: c# linq

我想创建一个CheckboxList,其中检查用户的角色,并显示所有可用选项,UI是可以的。但是下面的代码不起作用。

        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看起来不对。

1 个答案:

答案 0 :(得分:1)

你不想要包含,你想要any

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

contains看看某个给定元素是否在集合中,根本不是同一个东西,我很惊讶你的代码甚至编译了