[c#] Linq select object from list depending on objects attribute

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

This question is related to c# linq

The answer is


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);

if a.Correct is a bool flag for the correct answer then you need.

Answer answer = Answers.Single(a => a.Correct);

I think you are looking for this?

var correctAnswer = Answers.First(a => a.Correct);

You can use single by typing :

var correctAnswer = Answers.Single(a => a.Correct);

Few things to fix here:

  1. No parenthesis in class declaration
  2. Make the "correct" property as public
  3. And then do the selection

Your code will look something like this

List<Answer> answers = new List<Answer>();
/* test
answers.Add(new Answer() { correct = false });
answers.Add(new Answer() { correct = true });
answers.Add(new Answer() { correct = false });
*/
Answer answer = answers.Single(a => a.correct == true);

and the class

class Answer
{
   public bool 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);

Of course!

Use FirstOrDefault() to select the first object which matches the condition:

Answer answer = Answers.FirstOrDefault(a => a.Correct);

Otherwise use Where() to select a subset of your list:

var answers = Answers.Where(a => a.Correct);

Answers = Answers.GroupBy(a => a.id).Select(x => x.First());

This will select each unique object by email