I have a list of objects
class Answer
{
bool correct;
}
List<Answer> Answers = new List<Answer>();
Is there a way in linq for me to select an object depending on its attribute?
So far I have
Answer answer = Answers.Single(a => a == a.Correct);
But it does not work
First, Single
throws an exception if there is more than one element satisfying the criteria. Second, your criteria should only check if the Correct
property is true
. Right now, you are checking if a
is equal to a.Correct
(which will not even compile).
You should use First
(which will throw if there are no such elements), or FirstOrDefault
(which will return null
for a reference type if there isn't such element):
// this will return the first correct answer,
// or throw an exception if there are no correct answers
var correct = answers.First(a => a.Correct);
// this will return the first correct answer,
// or null if there are no correct answers
var correct = answers.FirstOrDefault(a => a.Correct);
// this will return a list containing all answers which are correct,
// or an empty list if there are no correct answers
var allCorrect = answers.Where(a => a.Correct).ToList();
I assume you are getting an exception because of Single. Your list may have more than one answer marked as correct, that is why Single
will throw an exception use First, or FirstOrDefault();
Answer answer = Answers.FirstOrDefault(a => a.Correct);
Also if you want to get list of all items marked as correct you may try:
List<Answer> correctedAnswers = Answers.Where(a => a.Correct).ToList();
If your desired result is Single
, then the mistake you are doing in your query is comparing an item with the bool value. Your comparison
a == a.Correct
is wrong in the statement. Your single query should be:
Answer answer = Answers.Single(a => a.Correct == true);
Or shortly as:
Answer answer = Answers.Single(a => a.Correct);
Your expression is never going to evaluate.
You are comparing a
with a property of a
.
a
is of type Answer. a.Correct
, I'm guessing is a boolean.
Long form:-
Answer = answer.SingleOrDefault(a => a.Correct == true);
Short form:-
Answer = answer.SingleOrDefault(a => a.Correct);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With