Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq select object from list depending on objects attribute

Tags:

c#

linq

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

like image 737
Wesley Skeen Avatar asked Nov 05 '12 10:11

Wesley Skeen


3 Answers

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();
like image 151
Groo Avatar answered Nov 13 '22 00:11

Groo


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);
like image 33
Habib Avatar answered Nov 13 '22 00:11

Habib


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);
like image 5
Paul Alan Taylor Avatar answered Nov 13 '22 00:11

Paul Alan Taylor