How do I convert this into LinQ?
SELECT *
FROM YourTable
WHERE id IN (
SELECT MAX(id) FROM YourTable GROUP BY alarmId, alarmUnit
)
tried so far below but doesn't work
var a= from x in YourTable .ToList()
group x by new { x.alarmId, x.alarmUnit} into g
from x1 in YourTable
where x1.ID == (from x2 in g select x2.ID).Max()
select x1;
Thanks,
Try this:
var a= from x in YourTable .ToList()
group x by new { x.alarmId, x.alarmUnit} into g
select new
{
alarmId = g.Key.alarmId,
alarmUnit = g.Key.alarmUnit,
id = g.Max(b => b.id)
};
var a = from x in YourTable
where (
from y in YourTable
group y by new { y.alarmId, y.alarmUnit } into g
select g.Max(z => z.ID)
).Contains(x.ID)
select x;
This should yield following SQL
SELECT [t0].[ID] AS [ID], [t0].[alarmId] AS [alarmId], ...
FROM [YourTable] AS [t0]
WHERE EXISTS(
SELECT NULL AS [EMPTY]
FROM (
SELECT MAX([t1].[ID]) AS [value]
FROM [YourTable] AS [t1]
GROUP BY [t1].[alarmId], [t1].[alarmUnit]
) AS [t2]
WHERE [t2].[value] = [t0].[ID]
)
The exists in this case is equivalent to in . Also, if the ID field is not a key, it will return all records with matching max ID, per your original question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.