我正在使用C#和T-SQL。
我试图从符合特定条件的表格中获取最新记录的日期,并且我被困在匹配部分。目前我所拥有的是:
date = (DateTime)(context.corresps.OrderByDescending(x => x.tevent).Select(x => x.tevent).FirstOrDefault());
我无法弄清楚如何添加到此声明:
WHERE cmethod = 'W'
我可以将其重写为标准的LINQ查询,但我正在努力改善自己。感谢您的帮助。
答案 0 :(得分:2)
除非我遗漏了一些东西:
var date = context.corresps.OrderByDescending(x => x.tevent)
.Where(x => x.cMethod == "W")
.Select(x => x.tevent)
.FirstOrDefault());
答案 1 :(得分:1)
我认为你误解了整个概念。
当你有
时context.corresps.OrderByDescending(x => x.tevent).FirstOrDefault()
您获得的字段corresp
tevent
您可以使用where this子句为查询添加条件
context.corresps.Where(x => x.cmethod = 'W').OrderByDescending(x => x.tevent).FirstOrDefault()
最后,除非您在corresp
课程中实施了此功能,否则无法将DateTime
强制转换为corresp
。所以你应该从对象本身获得你想要的日期时间。最终的代码将是这样的
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