我在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();
答案 0 :(得分:46)
使用:
var result = Sample.OrderByDescending(t => t.Date).First();
答案 1 :(得分:20)
要按日期获取最大Sample
值,而不必排序(这不是真正必要的最大值):
var maxSample = Samples.Where(s => s.Date == Samples.Max(x => x.Date))
.FirstOrDefault();
答案 2 :(得分:2)
List<Sample> q = Sample.OrderByDescending(T=>T.Date).Take(1).ToList();
但我认为你想要
Sample q = Sample.OrderByDescending(T=>T.Date).FirstOrDefault();
答案 3 :(得分:1)
var lastInstDate = model.Max(i=>i.ScheduleDate);
我们可以从这个模型获得最大日期。
答案 4 :(得分:0)
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;
结果: 史蒂夫 罗恩 内存 约翰 比尔
答案 5 :(得分:0)
var result= Sample.OrderByDescending(k => k.ID).FirstOrDefault().Date;
这是最好的方法