Help with Querie in Linq C#

Asked

Viewed 85 times

1

I have a message table in the following scheme:

Id | osID |Interessado | Remetente | Destinatario | Msg
--------------------------------------------------
1  |  2   |João        |   João    |   Maria      |bla bla bla...
2  |  2   |João        |   Maria   |   João       |ble ble ble...
3  |  3   |Erik        |   Erik    |   Mark       |O Amadeu ganhou a promoção...
4  |  3   |Erik        |   Mark    |   Erik       |Eu sabia...
5  |  3   |Erik        |   Mark    |   Erik       |Vou pedir as contas...
6  |  4   |Jake        |   Jake    |   Mara       |As oito da noite lá em casa...

The scenario I need is that each user who is logged in, load their conversations, then I have the following querie:

var mensagens = from p in db.Chats
                            orderby p.Id descending
                            where p.Remetente == MinhaPessoa.Usuario || p.Destinatario == MinhaPessoa.Usuario
                            select p;

This querie returns all records if I am sender or recipient. Now, how do I group that by Order of Service(osID) and Interested, and that the last message be displayed?

  • 1

    I think this is it but I won’t be able to test it, if it works it confirms it for me Check it as Resp ok :D var messages = (from p in db.Chats orderby p.Id Descending Where p.Sender == Pathname.User || p.Destinatario == Pathname.User group p by new {p.osID,p.Interested} int Pn select { Pn.Msg }). First();

  • gave everything ok, but the final part the intelissense did not understand what would be the "Pn" of int Pn select { Pn. Msg }). First(); ??

  • 1

    opa, it’s not int, it’s in

  • almost la Lucas,, I did and it stayed that way. I made some modifications and it looked like this: var msg = from p in db.Chats orderby p.Chatid Descending group p by new { p.Contaid, p.Interestingfrom } into g select new { interested = g.Key, Account = g.Select(m => m.Message). First() }; since it only returns msg, I wanted to return the Interested and the OSID, or account

  • beauty, Claudinei! answer your own question for case one day someone with the same doubt search and find your ;)

  • Thank you very much Lucas. I learned a lot!

Show 1 more comment

1 answer

2

With the help of @Lucas Miranda I was able to implement the following:

var msg = from p in db.Chats 
orderby p.ChatId descending 
group p by new { p.ContaId, p.InteressadoId } 
into g select new { Interessado = g.Key, Conta = g.Select(m => m.ChatId).First() };

Instead of selecting the fields, I take the primary key and the other fields implement through it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.