private List <ChatMainInboxModel> GetMessages() { var currentUserId = User.Identity.GetUserId(); var messages = _chatRepository.Chats(User.Identity.GetUserId()).OrderByDescending(t => t.SentDate).ToList(); var lastMessages = new List <ChatMainInboxModel>(); while (messages.Any()) { if (messages.First().UserFrom.Id != currentUserId) { lastMessages.Add(new ChatMainInboxModel { Seen = messages.First().Seen, SentDate = messages.First().SentDate, Title = messages.First().Title, UserId = messages.First().UserFrom.Id, UserName = messages.First().UserFrom.Name + " " + messages.First().UserFrom.Surname }); string id = messages.First().UserFrom.Id; messages.RemoveAll(m => m.UserFrom.Id == id || m.UserTo.Id == id); } else { if (!messages.Any()) { break; } lastMessages.Add(new ChatMainInboxModel { Seen = true, SentDate = messages.First().SentDate, Title = messages.First().Title, UserId = messages.First().UserTo.Id, UserName = messages.First().UserTo.Name + " " + messages.First().UserTo.Surname }); string id = messages.First().UserTo.Id; messages.RemoveAll(m => m.UserFrom.Id == id || m.UserTo.Id == id); } } return(lastMessages); }