Reputation: 111
I have a list of answer entities (list size is 50-2000 items - entities have many more properties than shown here) I want a linq query to select all the entities for those who have not got an answer correct yet so my output list of entities would exclude all entities by fred and harry from the following table because they each have a correct answer - and include all entities with answers by bob and bill - I have to select on isCorrect and not on the answer itself as the answers are scrambled when presented to the user and I need the full entity as well.
- username | answer | isCorrect | .....
- fred | a | false exclude as he has 1 correct
- fred | d | false exclude as he has 1 correct
- fred | b | false exclude as he has 1 correct
- fred | a | true exclude as he has 1 correct
+ bob | a | false need this entity
+ bob | b | false need this entity
+ bill | a | false need this entity
+ bill | b | false need this entity
- harry | a | false exclude as he has 1 correct
- harry | b | true exclude as he has 1 correct
- harry | c | false exclude as he has 1 correct
I can get a list of users with no correct answers
var usersWithNoCorrectAnswers = entities
.GroupBy(a => a.UserName)
.Where(g => g.Any(x => !x.IsCorrect))
.Select(g => g.Key)
.ToList();
but I'm not sure how to get a list of entities with no correct answer thanks
Upvotes: 0
Views: 96
Reputation: 32266
To get all the entities for the users that got all their answers wrong you can group on the username and filter out users that got any correct. Then just select the entities for the groups and flatten the results.
var results = entities.GroupBy(a => a.UserName(
.Where(g => !g.Any(a => a.IsCorrect))
.SelectMany(g => g)
.ToList();
Upvotes: 2
Reputation: 247018
but I'm not sure how to get a list of entities with no correct answer
var noCorrectAnswers = entities
.GroupBy(q => q.UserName)
.Where(g => !g.Any(a => a.IsCorrect))
.SelectMany(g => g)
.ToList();
Upvotes: 1
Reputation: 611
I think you need something like this:
var results = entities.GroupBy(a => a.UserName(
.Where(g => !g.Any(a => a.IsCorrect))
.SelectMany(g => g.Select(a =>
new {
username = a.username,
answer = a.answer,
...
}
))
.Distinct()
.ToList();
Or
var results = entities.GroupBy(a => a.UserName(
.Where(g => !g.Any(a => a.IsCorrect))
.SelectMany(g => g.Select(a => a))
.Distinct()
.ToList();
Upvotes: 1