简体   繁体   中英

linq select with group by

I made a simple messaging system and my SQL table is like

id | from_id | to_id | text
---------------------------
1  |    10   |  11   |  abc
2  |    11   |  10   |  cde
3  |    10   |  11   |  fgh

for example I'm "user 10" and when I send message to "user 11" I have to see my message box like

---> 11 fgh

and when user 11 sends me a reply ex. "hij" I have to see result like

11 hij

its like twitter dm system. If I'm the last one who sends the message, I have to see who I send the message to and my message content.

return (from data in db.user_messages.AsEnumerable()
        where data.id == ((from messages in db.user_messages
                           where messages.from_id == data.from_id
                           orderby messages.message_created_at descending
                           select new
                           {
                               messages.id
                           }).Take(1).FirstOrDefault().id) &&
                           data.to_id == user.UserId
                           orderby data.message_created_at descending
        select data).ToList();

With this code I can only see when user sends me a message, I can't get any result if I'm the one who sends the last message.

How can I improve this select? Thank you.

If you want to select last message from each conversation of user:

from um in db.user_messages
where um.from_id == user.UserId || um.to_id == user.UserId
let otherId = (um.from_id == user.UserId) ? um.to_id : um.from_id
group um by otherId into g
select g.OrderByDescending(um => um.message_created_at).FirstOrDefault()

NOTE: This query will be translated into SQL and executed on database side.

Displaying conversation can look like:

foreach(var message in query.OrderBy(um => um.message_created_at))
   Console.WriteLine("{0}{1}{2}",
      message.from_id == user.UserId ? "--->" : "",
      message.from_id == user.UserId ? message.to_id : message.from_id,
      message.text);

BTW you can select otherId from query to avoid additional id checks.

If you wish to get the last message

db.user_messages.Where(m => 
(m.from_id == user.UserId && m.to_id == otherUser.UserId) ||
(m.from_id == otherUser.UserId && m.to_id == user.UserId))
.OrderByDescending(m => m.message_created_at).First();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM