RobD
RobD

Reputation: 1704

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?

Upvotes: 8

Views: 411

Answers (4)

Kishore Kumar
Kishore Kumar

Reputation: 12874

change = to == in your linq code.

Upvotes: 0

Keith Rousseau
Keith Rousseau

Reputation: 4485

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

Upvotes: 4

Scott M.
Scott M.

Reputation: 7347

your line

opt => opt.Selected = true

needs another equals sign:

opt => opt.Selected == true

Upvotes: 7

Aliostad
Aliostad

Reputation: 81680

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

Upvotes: 14

Related Questions