Linq To Entities Grouping

时间:2012-08-23 07:03:08

标签: c# .net linq-to-entities

我有一个包含成员的消息列表:

  

Text = m.Text,User = m.User,Date = m.Date

此列表包含所有消息,如

Text = "How Are You"
User = "Michael"
Date = "1/1/12"

Text = "Well Done"
User = "Michael"
Date = "2/1/12"

Text = "Who?"
User = "John"
Date = "1/1/12"

我恳请得到来自同一个人的最新消息,这些消息不会显示来自同一个人的多条消息,只给出最后一封消息:

Text = "Well Done"
User = "Michael"
Date = "2/1/12"

Text = "Who?"
User = "John"
Date = "1/1/12"

如你所见;我想删除同一个人的上一条消息。

我目前正在使用:

var messages = (from m in mList select new
{
Text = m.Text, 
User = m.User, 
Date = m.Date
}).ToList();

我应该在此查询中添加什么来实现我的目标?

谢谢!

2 个答案:

答案 0 :(得分:2)

var messages = (from m in mList select new
{
   Text = m.Text, 
   User = m.User, 
   Date = m.Date
})
.GroupBy(m => m.User)
.Select(g => g.OrderByDescending(m => m.Date).First())
.ToList();

答案 1 :(得分:0)

try{
    var messages = (from m in mList select new
    {
        Text = m.Text, 
        User = m.User, 
        Date = DateTime.Parse(m.Date)
    })
    .GroupBy(x => x.User).Select(x => x.First()).ToList();
}catch{}

因为日期不是字符串可排序的......