2
I have the following query:
query = from p in db.pessoa
join f in db.pessoa_origem on p.Pessoa_Origem_Id equals f.Id
join s in db.pessoa_status on p.Pessoa_Status_Id equals s.Id
join c in db.contato on p.Id equals c.Pessoa_Id
select p;
And I want to order by c.data
.
The cardinality of the relationship between person and contact is 1 : n. That is, a person may have 0 or n contacts.
When I use the code:
query = query.OrderByDescending(u => u.contato.Count > 0 ? u.contato.OrderByDescending(t => t.Id).FirstOrDefault().Data : null);
It works though, it’s catching the biggest Id
among the contacts to sort by his date. What I need is to pick up the contact with the highest date and sort by date. However, the following part does not work:
query = query.OrderByDescending(u => u.contato.Count > 0 ? u.contato.OrderByDescending(t => t.Data).FirstOrDefault().Data : null);
Could anyone help in how to solve this problem?
What do you mean by "the following passage does not work"? Does not compile or behave as you want?
– Jéf Bueno
From what I understand, you want an object returned
Pessoa
and aDateTime
(orDateTime?
) referring to this person’s last contact. First thing you need to see is this ternary condition at the end of the last query, because ifdb.contato.data
be the typeDateTime
, you can’t make that condition by returningnull
– Jéf Bueno
Hi Jéferson! It compiles, but returns with empty list and gives error... It is that I need to sort the result... For example: Person: Johnny Contacts: 03/15/2015 and 03/17/2015 Person: Mariazinha: Contacts: 03/14/2015 and 03/16/2015 In the result, if ordered by increasing date should appear: Mariazinha - 03/16/2015 Johnny - 03/17/2015 But if ordered by decreasing date, should appear: Joãozinho - 17/03/2015 Mariazinha - 16/03/2015 This order that I need to put... but in select, should come the contact, whose date is the highest...
– Felipe Bulle
I answered your question, I only had a doubt but, actually only a reinforcement, people who have no contact will not appear in this selection, OK?
– user46523