public IActionResult Index(string searchTerm) { var user = userService.GetCurrentUser(); var userFriends = user.Friends; // Take user's friends whose names begin contain the search term. if (!string.IsNullOrWhiteSpace(searchTerm)) { userFriends = userFriends.Where(user => user.FirstName.ToLower().Contains(searchTerm.ToLower()) || user.LastName.ToLower().Contains(searchTerm.ToLower())).ToList(); } var startedChatViewModels = new List <StartedChatViewModel>(); foreach (var friend in userFriends) { var friendViewModel = mapper.Map <FriendViewModel>(friend); var lastFriendMessage = messengerService.GetLastUsersMessage(user.Login, friend.Login); var lastMessageViewModel = mapper.Map <MessageViewModel>(lastFriendMessage); if (lastMessageViewModel != null) { lastMessageViewModel.Text = TruncateLongString(lastMessageViewModel.Text, 40); } startedChatViewModels.Add(new StartedChatViewModel() { Friend = friendViewModel, LastMessage = lastMessageViewModel }); } startedChatViewModels = startedChatViewModels.OrderByDescending(startedChat => startedChat.LastMessage?.Date) .ToList(); return(View(startedChatViewModels)); }