问题描述
大家好,
我对linq语句有一些疑问.这是我的桌子,名为Tblactivity
activityid bigint
studentid bigint
activitydate datetime
说明nvarchar(Max)
状态位
我用数据填充Tblactivity.如
activityid |学生证|活动日期|描述|状态
1 | 1 | 2012-08-15 00:30:00 | descA | A
2 | 3 | 2012-08-16 12:30:00 | descAA | A
3 | 2 | 2012-08-16 13:15:12 | descB | B
4 | 3 | 2012-09-02 10:20:11 |说明| A
5 | 3 | 2012-09-02 11:00:00 |说明| A
6 | 4 | 2012-09-02 14:00:00 | descAA | S
所以我开发linq以获得学生ID = 3的详细信息.这是我的linq代码
Hi all,
I have some issue with linq statement. here is my table, named Tblactivity
activityidbigint
studentid bigint
activitydate datetime
descriptionnvarchar(Max)
statusbit
i populate Tblactivity with data. such as
activityid| studentid | activitydate | description | status
1| 1| 2012-08-15 00:30:00 | descA | A
2| 3| 2012-08-16 12:30:00| descAA | A
3| 2| 2012-08-16 13:15:12| descB | B
4| 3| 2012-09-02 10:20:11| descS | A
5| 3| 2012-09-02 11:00:00| descS | A
6| 4| 2012-09-02 14:00:00| descAA | S
so i develop linq to get detail information of student id = 3. here is my linq code
public List<Tblactivity> getStudents(long studentid, string status)
{
studentdatacontext db=new studentdatacontext;
try
{
List<Tblactivity> BG = (from o in db.Tblactivities
orderby o.activitydate descending where o.studentid == studentid &&
o.activitydate.Value.Month <= DateTime.Now.Month &&
o.activitydate.Value.Month >= DateTime.Now.Date.AddMonths(-1)&&
o.status == status select o).ToList();
return BG;
}
catch (Exception e)
{
throw e;
}
}
所以我根据学生ID = 3获得了所有记录,但是当活动日期相同(最新记录)时,我只想要一条记录.
我读了一些文章,他们建议我使用MAX().但我不知道如何发展以适应上述功能.请建议我.
谢谢,
df
so i got all of the records according to student id = 3.but i want only one record when the activitydate is same (the latest record).
i read some article they suggest me to use MAX(). but i don''t know how to develop to suit with the above function. pls suggest me.
Thanks,
df
推荐答案
List<Tblactivity> BG= (from o in db.Tblactivities
where o.studentid == studentid &&
o.activitydate.Value.Month <= DateTime.Now.Month &&
o.activitydate.Value.Month >= DateTime.Now.Date.AddMonths(-1) &&
o.status == status
&& o.activitydate == (from n in db.Tblactivities where n.studentid == o.studentid && Convert.ToString(n.activitydate).Substring(0, 10) == Convert.ToString(o.activitydate).Substring(0, 10) orderby n.activitydate descending select n).Max(l => l.activitydate)
select o).Distinct().ToList();
List<tblactivity> BG = (from o in db.Tblactivities
orderby o.activitydate descending where o.studentid == studentid &&
o.activitydate.Value.Month <= DateTime.Now.Month &&
o.activitydate.Value.Month >= DateTime.Now.Date.AddMonths(-1)&&
o.status == status select o).ToList().Distinct();
这篇关于从linq检索重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!