我有一个具有这样记录的数据表...

JID                      Date                     RecentChatString
-----------------------------------------------------------------------
[email protected]         11/Nov/2013 11:53:00        Hi
[email protected]         11/Nov/2013 11:53:10        Hello
[email protected]         11/Nov/2013 11:54:00        Good Morning
[email protected]         11/Nov/2013 12:03:00        Ok
[email protected]         11/Nov/2013 12:05:10        Please reply
[email protected]         11/Nov/2013 12:15:00        Good after noon
[email protected]         11/Nov/2013 12:15:50        Ok bye


我想获取按日期排序的十大不同记录,并且仅表示每个JID的最近聊天记录。

JID                      Date                     RecentChatString
-----------------------------------------------------------------------
[email protected]         11/Nov/2013 12:05:10        Please reply
[email protected]         11/Nov/2013 12:15:50        Ok bye


现在我有这样的代码。使用此代码,我可以获得按日期排序的前10条记录。
但是,它包含重复的JID's。请帮我。 (recent_index是一个数据表)

DataRow recent_dr = recent_index.NewRow();
recent_dr["JID"] = RosterId;
recent_dr["Date"] = DateTime.Now;
recent_dr["RecentChatString"] = _chatline;
recent_index.Rows.Add(recent_dr);

DataTable dtt = new DataTable("RecentChats");
dtt.Columns.Add("JID", Type.GetType("System.String"));
dtt.Columns.Add("Date", Type.GetType("System.DateTime"));
dtt.Columns.Add("RecentChatString", Type.GetType("System.String"));

IEnumerable<DataRow> recentTen = recent_index.AsEnumerable().OrderByDescending(x=>x["Date"]).Take(10);
recentTen.CopyToDataTable(dtt, LoadOption.OverwriteChanges);

dtt.WriteXml(s + "\\FPhoneData\\chats\\index.xml");

最佳答案

DataTable recentTen = recent_index.AsEnumerable()
    .OrderByDescending(r => r.Field<DateTime>("Date"))
    .GroupBy(r => r.Field<string>("JID"))
    .Take(10)
    .Select(g => g.First())
    .CopyToDataTable();

关于c# - 如何按日期获取前10个不同行的顺序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20117221/

10-09 00:15