我在MS Sql Server中有这个名为sample的表,其中包含以下值:
ID Date Description
1 2012/01/02 5:12:43 Desc1
2 2012/01/02 5:12:48 Desc2
3 2012/01/03 5:12:41 Desc3
4 2012/01/03 5:12:43 Desc4
现在我想写LINQ查询,结果将是这样的:
4 2012/01/03 5:12:43 Desc4
我写了这个,但它不起作用:
List<Sample> q = (from n in Sample.Max(T=>T.Date)).ToList();
使用:
var result = Sample.OrderByDescending(t => t.Date).First();
要按日期获得最大Sample
值而不必排序(这不是真正必要的,只是获得最大值):
var maxSample = Samples.Where(s => s.Date == Samples.Max(x => x.Date))
.FirstOrDefault();
List<Sample> q = Sample.OrderByDescending(T=>T.Date).Take(1).ToList();
但我想你想要
Sample q = Sample.OrderByDescending(T=>T.Date).FirstOrDefault();
var lastInstDate = model.Max(i=>i.ScheduleDate);
我们可以像这样从模型中获得最大日期。
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 }
};
var orderByDescendingResult = from s in studentList
orderby s.StudentName descending
select s;
结果:Steve Ron Ram John Bill