Выберите последние два ряда истории чата linq - PullRequest
0 голосов
/ 04 мая 2020

У меня есть таблица ChatMessage, и я хочу выбрать историю чатов пользователя в качестве списка последнего сообщения, которое он / она имеет с другими или с самим собой, как приложение whast.

при открытии приложения Whats вы увидите список из вашей истории чатов, которые показывают последний чат.

схема таблицы выглядит следующим образом:

SenderId    ReciverId    Message
--------------------------------
1           2            hello
1           2            how are you?
2           1            hey
2           1            i'm fine
2           2            for myself
2           3            are you there?

Я пытался с этим запросом:

SELECT MAX(SenderID), ReciverID, Message
FROM ChatMessages
WHERE SenderID = 2 OR ReciverID = 2
GROUP BY SenderID, ReciverID order by SenderID

результат для этого запрос:

    senderId    ReciverId    Message
    --------------------------------
    1           2            how are you?
    2           1            i'm fine
    2           2            for myself
    2           3            are you there?

строки 1 и 2 должны быть объединены и просто показать: 2 1 i'm fine

и результат, который я ищу:

    senderId    ReciverId    Message
    --------------------------------
    2           1            i'm fine
    2           2            for myself
    2           3            are you there?

в чем решение? а если можно в линк или лямбду?

1 Ответ

0 голосов
/ 07 мая 2020

Я получил это с помощью groupBy и получил 2 последних сообщения от каждого партнера, а затем использовал отдельный (от morelinq) для удаления дубликата.

string uid =  "a90566ab-eef7-4f57-8e96-a3b7cc8ce786";               

var chatIdsQuery = _context.ChatMessages
    .Where(o => o.SenderID.Equals(uid) || o.ReciverID.Equals(uid))                    
    .Select(x => new
    {
         x.Id,
        x.ReciverID,
        x.SenderID
    })                     
    .GroupBy(g => new { g.SenderID, g.ReciverID } )
    .Select(k => new {
        Id = k.Max(x => x.Id),
        PartnerId = k.Key.SenderID.Equals(uid) ? k.Key.ReciverID : k.Key.SenderID,
        //CreateTime = k.Max(x => x.CreateTime)
    })
    .OrderByDescending(d => d.Id)                  
    .AsQueryable(),
    .DistinctBy(i => i.PartnerId);  // <============= just remove dublicate

var chatListQuery = from l in chatIdsQuery
               join x in _context.ChatMessages on l.Id equals x.Id
               orderby x.CreateTime descending
               select (new
               {
                   x.Id,
                   l.PartnerId,
                   x.Text,
                   x.CreateTime
               });
var chatList = chatListQuery.ToList();

и для asyn c:

var chatList = await chatListQuery.ToListAsync();
chatList = chatList.DistinctBy(i => i.PartnerId).ToList();

или:

chatList = chatList.GroupBy(x => x.PartnerId).Select(x => x.First()).ToList();
...