Creating a collection of SelectListItem with LINQ

后端 未结 2 1463
终归单人心
终归单人心 2021-02-07 03:14

I\'m trying to display a dropdown list of users in my view. Here is the code I\'m using in my controller method:

var users = _usersRepository.Users.Select(u =>         


        
相关标签:
2条回答
  • 2021-02-07 04:05

    ToString() can only be used in Linq to Objects. A simple solution is to insert .ToList() as follows:

    var users = _usersRepository.Users.ToList().Select(u => new SelectListItem
                                        {
                                            Text = u.FirstName + " " + u.LastName,
                                            Value = u.UserID.ToString()
                                        });
    
    return View(new MyViewModel { Users = users });
    

    This is going to return all users from your User table. If you can reduce the amount of users obtained from the database your query will be more efficient, e.g.

    var users = _usersRepository.Users.Where( u => .... ).ToList().Select(u => new SelectListItem
                                        {
                                            Text = u.FirstName + " " + u.LastName,
                                            Value = u.UserID.ToString()
                                        });
    
    return View(new MyViewModel { Users = users });
    
    0 讨论(0)
  • 2021-02-07 04:11

    I think you're looking for SqlFunctions

    using System.Data.Objects.SqlClient;
    
    var users = _usersRepository.Users.Select(u => new SelectListItem
                                        {
                                            Text = u.FirstName + " " + u.LastName,
                                            Value = SqlFunctions.StringConvert((double?)u.UserID)
                                        }
    
    return View(new MyViewModel { Users = users });
    
    0 讨论(0)
提交回复
热议问题