C# LINQ 中的最大日期记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9143146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:09:36  来源:igfitidea点击:

max date record in LINQ

c#.netsql-serverlinqmax

提问by Salah Sanjabian

I have this table named sample with these values in MS Sql Server:

我在 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

Now I want to write LINQ query that result will be this:

现在我想编写 LINQ 查询,结果将是这样的:

4    2012/01/03 5:12:43    Desc4

I wrote this but it doesn't work:

我写了这个,但它不起作用:

List<Sample> q = (from n in  Sample.Max(T=>T.Date)).ToList();

采纳答案by Kirill Polishchuk

Use:

用:

var result = Sample.OrderByDescending(t => t.Date).First();

回答by Albin Sunnanbo

List<Sample> q = Sample.OrderByDescending(T=>T.Date).Take(1).ToList();

But I think you want

但我想你想要

Sample q = Sample.OrderByDescending(T=>T.Date).FirstOrDefault();

回答by BrokenGlass

To get the maximum Samplevalue by date withouthaving to sort (which is not really necessary to just get the maximum):

要按Sample日期获取最大值无需排序(这并不是获取最大值所必需的):

var maxSample  = Samples.Where(s => s.Date == Samples.Max(x => x.Date))
                        .FirstOrDefault();

回答by Adarsh Babu PR

var lastInstDate = model.Max(i=>i.ScheduleDate);

We can get max date from the model like this.

我们可以像这样从模型中获取最大日期。

回答by Parag555

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;

Result : Steve Ron Ram John Bill

结果:史蒂夫·罗恩·拉姆·约翰·比尔

回答by Rasindu De Alwis

var result= Sample.OrderByDescending(k => k.ID).FirstOrDefault().Date;

This is the best way to do this

这是执行此操作的最佳方法