你能帮我改进一下这段代码吗?
var orderNo = "1234";
var maxValue = MyTable.Where(x => x.OrderNo == orderNo )
.OrderByDescending(x => x.Filename)
.Select(x => x.Filename)
.FirstOrDefault();
var list = (from x in MyTable
where x.OrderNo == orderNo && x.Filename == maxValue
select x).Distinct();
list.Dump();
是否可以将这2个Linq查询改进为1并避免查询2次我的数据库。类似的东西:
var list = (from x in MyTable
where x.OrderNo == orderNo && MaxValue(x.Filename)
select x)
.Distinct();
答案 0 :(得分:3)
您可以使用GroupBy
:
var list = MyTable
.Where(x => x.OrderNo == "1234") // or var1
.GroupBy(x => x.Filename)
.OrderByDescending(g => g.Key)
.First()
.Distinct();
答案 1 :(得分:1)
尝试
var list = (
from x in MyTable
where x.OrderNo == var1 &&
x.Filename == MyTable.Where(x => (x.OrderNo == "1234")).Max(p => p.Filename)
select x
).Distinct();
答案 2 :(得分:1)
为什么不呢:
MyTable.Where(x => x.OrderNo == "1234")
.Max(x => x.Filename);
您将获得具有最大文件名的所有记录。