Dear All I have this table as shown below
| ID | Student_Name | Marks | Course_ID |
| 1 | ABC | 78 | 1 |
| 2 | HHH | 88 | 3 |
| 3 | ABC | 89 | 1 |
| 4 | ABC | 99 | 1 |
| 5 | CCC | 67 | 2 |
| 6 | HHH | 76 | 3 |
From above table I would like to get the records I would like to take one record for each course ID but that records must be the latest one for that course ID like for course ID =1 the record I need to get should have ID =4 as this is the latest for course _ID 1 , same as for HHH I need to get row 6 and 6 is the latest record this is auto increament Id , and for CCC as there is only one record so I need to get 5th row, how to get this in linq query

Sachin SinghRank #66 · 26.2K reputationPosted Jan 18, 2024, 2:16 AM EST
@Pakeeza it is even simpler in LINQ
var latestRecords = yourList .GroupBy(s => s.Course_ID) .Select(group => group.OrderByDescending(s => s.ID).First()) .ToList();Amit MohantyRank #112 · 20K reputationPosted Jan 18, 2024, 1:05 AM EST
Check this:
List students = new List { new Student { ID = 1, Student_Name = "ABC", Marks = 78, Course_ID = 1 }, new Student { ID = 2, Student_Name = "HHH", Marks = 88, Course_ID = 3 }, new Student { ID = 3, Student_Name = "ABC", Marks = 89, Course_ID = 1 }, new Student { ID = 4, Student_Name = "ABC", Marks = 99, Course_ID = 1 }, new Student { ID = 5, Student_Name = "CCC", Marks = 67, Course_ID = 2 }, new Student { ID = 6, Student_Name = "HHH", Marks = 76, Course_ID = 3 } }; var latestRecords = students .GroupBy(student => student.Course_ID) .Select(group => group.OrderByDescending(student => student.ID).First()) .OrderBy(student => student.ID); foreach (var record in latestRecords) { Console.WriteLine($"ID: {record.ID}, Student_Name: {record.Student_Name}, Marks: {record.Marks}, Course_ID: {record.Course_ID}"); }Pakeeza172 reputationPosted Jan 18, 2024, 12:47 AM EST
I need this in Linq in SQL I did it thanks for the help
Pakeeza172 reputationPosted Jan 18, 2024, 2:10 AM EST
Uttam Chaturvedi can you share in LINQ
Pakeeza172 reputationPosted Jan 18, 2024, 2:46 AM EST
Dear both Uttam Chaturvedi,Sachin Singh the query Linq works as the SQL for this is provided by Uttam Chaturvedi so should I mark him even though you translated it into Linq there is no option to mark two as correct.
Uttam ChaturvediRank #477 · 5.2K reputationPosted Jan 17, 2024, 5:41 PM EST
Here you go with sql query to get latest records by id. Assuming your table name is student
SELECT * FROM dbo.student
WHERE id IN
(SELECT MAX(id) FROM dbo.student GROUP BY student_name)
Please accept answer, if you find it useful