简体   繁体   English

在符合特定条件的表中查找最新记录

[英]Finding the most recent record in a table matching a specific condition

I am using C# and T-SQL. 我正在使用C#和T-SQL。

I am trying to get the date of the most recent record from a table matching a specific condition, and I am stuck on the matching part. 我试图从符合特定条件的表中获取最新记录的日期,并且我被困在匹配部分。 Currently what I have is: 目前我所拥有的是:

date = (DateTime)(context.corresps.OrderByDescending(x => x.tevent).Select(x => x.tevent).FirstOrDefault());

What I am not able to figure out how to add to this statement is: 我无法弄清楚如何添加到此声明:

WHERE cmethod = 'W'

I could rewrite this as a standard LINQ query, but am trying to better myself. 我可以将其重写为标准LINQ查询,但我正在努力改善自己。 Thank you for any assistance. 谢谢你的帮助。

除非我遗漏了什么:

var date = context.corresps.OrderByDescending(x => x.tevent) .Where(x => x.cMethod == "W") .Select(x => x.tevent) .FirstOrDefault());

I think you misunderstood the whole concept. 我想你误解了整个概念。

when you have 当你有

context.corresps.OrderByDescending(x => x.tevent).FirstOrDefault()

you get a corresp that has the highest value for the field tevent 你会得到一个corresp具有用于该领域的最高值tevent

you can add a condition to your query by using where clause like this 您可以使用这样的where子句为查询添加条件

context.corresps.Where(x => x.cmethod = 'W').OrderByDescending(x => x.tevent).FirstOrDefault()

and at the end you can not cast your corresp to DateTime unless you have implemented this feature inside corresp class. 除非你在corresp类中实现了这个功能,否则最后你不能将你的correspDateTime so you should get a date time you want from the object itself. 所以你应该从对象本身获得你想要的日期时间。 final code is going to be something like this 最终代码将是这样的

var lastCorresp = context.corresps.Where(x => x.cmethod = 'W').OrderByDescending(x => x.tevent).Select(x => x.tevent).FirstOrDefault();
var lastDate = lastCorresp.tevent; //or any other field that represents the date time you want, since you've ordered your query by tevent field I assume that this field holds the date time you want to use

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM