ฉันใช้ LINQ บน IQueryable ที่ส่งคืนจาก NHibernate และฉันต้องการเลือกแถวที่มีค่าสูงสุดในสองฟิลด์
ฉันได้ทำให้บิตที่ฉันยึดติดง่ายขึ้น ฉันต้องการเลือกหนึ่งแถวจากตารางของฉันด้วยค่าสูงสุดในหนึ่งฟิลด์
var table = new Table { new Row(id: 1, status: 10), new Row(id: 2, status: 20) }
from u in table
group u by 1 into g
where u.Status == g.Max(u => u.Status)
select u
สิ่งนี้ไม่ถูกต้อง แต่ฉันไม่สามารถหาแบบฟอร์มที่ถูกต้องได้
BTW สิ่งที่ฉันพยายามจะบรรลุคือประมาณนี้:
var clientAddress = this.repository.GetAll()
.GroupBy(a => a)
.SelectMany(
g =>
g.Where(
a =>
a.Reference == clientReference &&
a.Status == ClientStatus.Live &&
a.AddressReference == g.Max(x => x.AddressReference) &&
a.StartDate == g.Max(x => x.StartDate)))
.SingleOrDefault();
ฉันเริ่มต้นด้วยแลมบ์ดาข้างต้น แต่ฉันใช้ LINQPad เพื่อลองใช้ไวยากรณ์สำหรับการเลือก Max ()
อัปเดต
การลบ GroupBy เป็นกุญแจสำคัญ
var all = this.repository.GetAll();
var address = all
.Where(
a =>
a.Reference == clientReference &&
a.Status == ClientStatus.Live &&
a.StartDate == all.Max(x => x.StartDate) &&
a.AddressReference == all.Max(x => x.AddressReference))
.SingleOrDefault();