0

I have a list of messages in db like so:

FromLoginId, ToLoginId, Message, CreateDate

  1. 1, 2, "some message", 2/2/2010
  2. 1, 2, "one more", 2/3/2010
  3. 4, 2, "from 4 message", 3/4/2010
  4. 5, 2, "from 5 mess", 1/3/2010
  5. 5, 2, "newer 5", 3/2/2011

I need to have a list of messages grouped by FromLoginId ordered by createDate starting from the newest first.

EDIT: List of messages with the first newest message from the FromLoginId group.

so for example for loginid 2 I would get this result:

FromLoginId, ToLoginId, Message, CreateDate

  1. 5, 2, "newer 5", 3/2/2011
  2. 4, 2, "from 4 message", 3/4/2010
  3. 1, 2, "one more", 2/3/2010

please help. thanks

ShaneKm
  • 20,823
  • 43
  • 167
  • 296
  • I think this has been answered here: http://stackoverflow.com/questions/755132/how-do-i-order-a-group-result-in-linq – Ucodia Jun 28 '11 at 07:23

2 Answers2

1

I think i figured it out. looks ok to me. can anyone please check it?

list.GroupBy(x => x.FromLoginId)
   .Select(x => x.OrderByDescending(y => y.CreateDate)
   .FirstOrDefault())
   .OrderByDescending(x => x.CreateDate)
Justin Grant
  • 44,807
  • 15
  • 124
  • 208
ShaneKm
  • 20,823
  • 43
  • 167
  • 296
0

If you group by FromLoginId you can't display the messages themselves, only the count of them, or any aggregate function that might interest you.

Variant
  • 17,279
  • 4
  • 40
  • 65