I would create this to be an extension method applied to List<user>
or whatever your userRepository.GetAll() returns so then in your code you can replace all of these usages with just
ViewData["Users"] = userRepository.GetAll().ToSelectList();
Edit code sample: There's 2 ways you could do this
public static List<SelectListItem> ToSelectList(this List<Agent> users)
{
List<SelectListItem> items = new List<int>();
foreach (var user in users)
{
var item = new SelectListItem { Text = user.FriendlyName,
Value = user.UserId.ToString() };
if (User.Identity.Name == user.UserName)
item.Selected = true;
items.Add(item);
}
return items;
}
And usage would be like
userRepository.GetAll().ToSelectList();
Or if you have problems with identity being in the extension method have
public static List<SelectListItem> ToSelectList(this List<Agent> users,
string selectedUserName)
{
List<SelectListItem> items = new List<int>();
foreach (var user in users)
{
var item = new SelectListItem { Text = user.FriendlyName,
Value = user.UserId.ToString() };
if (user.UserName == selectedUserName)
item.Selected = true;
items.Add(item);
}
return items;
}
And usage would be like
userRepository.GetAll().ToSelectList(User.Identity.Name);