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,
Singlethrows an exception if there is more than one element satisfying the criteria. Second, your criteria should only check if theCorrectproperty istrue. Right now, you are checking ifais equal toa.Correct(which will not even compile).You can also consider using
First(which will throw if there are no such elements), orFirstOrDefault(which will returnnullfor a reference type if there isn’t such element), orWherefollowed byToList(which will return all elements which satisfy the criteria):