2013-11-21 83 views
1

榮登10個不同行的次序我有一個DataTable中有記錄這樣的...如何通過日期

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 

我想按日期排序,前10個不重複的記錄,意味着只有最近的聊天每個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是一個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"); 
+0

什麼是數據庫引擎? –

+0

你嘗試過'.Distinct'嗎? –

+0

@MichaelPerrenoud XML ... –

回答

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

LINQ大師又來了。你的力量很強大。 –

+1

這不僅僅需要10個隨機JID並訂購它們嗎? Take()之前無需訂購? –

+0

@JoachimIsaksson:好點,編輯我的答案。第一種方法更高效,但會產生任意行,其中只考慮「JID」組的順序。 –

0

嘗試以下操作:

DataView view = new DataView(recent_index); 
DataTable distinctValues = view.ToTable(true, "JID", "Date" ...); 
0

使用.Distinct在您的收藏使用自定義類做不同的檢查

private class DistinctChecker: IEqualityComparer<YourRowType> 
{ 
} 
0

Tim的解決方案正確。這裏只是聲明性查詢的替代解決方案:

var latestMessages = 
    from r in recent_index.AsEnumerable() 
    group r by r.Field<string>("JID") into g 
    let latest = g.OrderByDescending(r => r.Field<DateTime>("Date")).First() 
    orderby latest.Field<DateTime>("Date") 
    select latest; 

var recent_dr = latestMessages.Take(10).CopyToDataTable();