convert SQL query in LinQ query

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,

Answers


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.


Need Your Help

jquery ajax Display multiple pages in div from multiple selection drop-down form

php jquery ajax

I have a multi select drop down. I need a div to be filled with pages based on the selections. I have this working for one selection at a time. I need it to also work when I select more than one op...