public List <DMPreviewVM> GetDMPreview(int myUserID) { List <DMPreviewVM> lista = new List <DMPreviewVM>(); foreach (var user in db.Users.ToList()) { Conversations conversation = db.Conversations .Where(x => x.User1ID == myUserID && x.User2ID == user.UserID).SingleOrDefault(); if (conversation == null) { conversation = db.Conversations .Where(x => x.User1ID == user.UserID && x.User2ID == myUserID).SingleOrDefault(); } if (conversation != null) { int usrID = -1; if (conversation.User1ID == myUserID) { usrID = conversation.User2ID; } else { usrID = conversation.User1ID; } Users usr = db.Users.Find(usrID); try { DMPreviewVM listItem = db.tsp_LatestMessage(conversation.User1ID, conversation.User2ID).Select(x => new DMPreviewVM { conversationID = conversation.ConversationID, nickname = usr.Nickname, username = usr.Username, content = x.Content, time = x.DateCreated, imgProfile = usr.ProfileImage }).SingleOrDefault(); if (db.tsp_LatestMessage(conversation.User1ID, conversation.User2ID).SingleOrDefault().SenderID == myUserID) { listItem.isMineLastMessage = true; } else { listItem.isMineLastMessage = false; } lista.Add(listItem); } catch (Exception) { } } } return(lista.OrderByDescending(x => x.time).ToList()); }