我有一个像这样的记录的数据表......
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'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 :(得分: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();
答案 1 :(得分:0)
请尝试以下操作:
DataView view = new DataView(recent_index);
DataTable distinctValues = view.ToTable(true, "JID", "Date" ...);
答案 2 :(得分:0)
在您的收藏集上使用.Distinct使用自定义类进行不同的检查
private class DistinctChecker: IEqualityComparer<YourRowType>
{
}
答案 3 :(得分:0)
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();