Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ WHERE method alters source collection

I have a method that returns a new list (it pertains to a multiple choice answer):

public static List<questionAnswer> GetAnswersWithSelections(this Questions_for_Exam__c question)
        {
            List<questionAnswer> answers = new List<questionAnswer>();

            answers.Add(new questionAnswer() { Ordinal = 1, AnswerText = question.AN1__c, Selected = (bool)question.Option1__c });

            ...

            return answers;
        }

If I examine the result of this method - I see the correct data, e.g. Red = False, Green = True, Blue = False

I then try to filter the returned result using the LINQ Where extension method:

List<questionAnswer> CorrectSelections = question.GetAnswersWithSelections();

var tmpA = CorrectSelections.Where(opt => opt.Selected = true);

When I materialise tmpA, 2 things happen:

  1. The data in the SOURCE list changes - E.g. Red = True, Green = True, Blue = True
  2. The data in tmpA is set to the same wrong data that the source list has been changed to

Any ideas?

like image 280
RobD Avatar asked Mar 27 '12 13:03

RobD


3 Answers

You need to use == and not =:

var tmpA = CorrectSelections.Where(opt => opt.Selected == true);

So when you search for condition, you were setting values. This is a common mistake, I fall for it as well :)

like image 173
Aliostad Avatar answered Nov 12 '22 14:11

Aliostad


your line

opt => opt.Selected = true

needs another equals sign:

opt => opt.Selected == true
like image 7
Scott M. Avatar answered Nov 12 '22 15:11

Scott M.


You want opt.Selected == true. You have a single =

like image 4
Keith Rousseau Avatar answered Nov 12 '22 14:11

Keith Rousseau