Roman
Roman

Reputation: 4513

How can you take only the last result with Linq

Ok, I didn't put the title right. I'll explain.

I've got a table with some exercise results. Mostly you've got a UserID, an ExerciseID, the Result and when was the result taken. The table is accessed using EF and Linq.

I want to get all the results for a given ExerciseID and take only the last one of each User. Using LINQ of course.

How can this be accomplished?

My Code (that takes all results) is as follows:

from e in models.ExerciseUserResults
where e.ExerciseID == ExerciseId
select e

This snippet will get all results for all users.

EDIT: an example

Let's say I've got this table

{<UserID>,<Result>} - {1,100},{1,200},{2,150},{2,250} - using JSON notation and without all the fields.

If the query is right - I would get [{1, 200},{2,250}]

Thanks

Upvotes: 0

Views: 140

Answers (1)

Servy
Servy

Reputation: 203813

The fact that you want one per user makes it pretty clear that you want to group the query by user. From there, you can project each group into just one item:

var query = from e in models.ExerciseUserResults
    where e.ExerciseID == ExerciseId
    group e by UserID into usersExercises
    select usersExercises.Last();

Upvotes: 6

Related Questions