Skip to main content
 首页 » 编程设计

c#之如何按日期排序前 10 个不同的行

2024年02月13日16unruledboy

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

JID                      Date                     RecentChatString 
-----------------------------------------------------------------------  
abc@gmail.com         11/Nov/2013 11:53:00        Hi  
abc@gmail.com         11/Nov/2013 11:53:10        Hello  
abc@gmail.com         11/Nov/2013 11:54:00        Good Morning  
def@gmail.com         11/Nov/2013 12:03:00        Ok  
abc@gmail.com         11/Nov/2013 12:05:10        Please reply  
def@gmail.com         11/Nov/2013 12:15:00        Good after noon  
def@gmail.com         11/Nov/2013 12:15:50        Ok bye 

我想获得按日期排序的前 10 个不同记录,并且仅表示每个 JID 的最近聊天..

JID                      Date                     RecentChatString 
----------------------------------------------------------------------- 
abc@gmail.com         11/Nov/2013 12:05:10        Please reply 
def@gmail.com         11/Nov/2013 12:15:50        Ok bye 

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

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();