LINQ WHERE方法改变源集合

Rob*_*obD 8 c# linq collections

我有一个返回新列表的方法(它与多项选择答案有关):

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;
        }
Run Code Online (Sandbox Code Playgroud)

如果我检查这个方法的结果 - 我看到正确的数据,例如Red = False,Green = True,Blue = False

然后我尝试使用LINQ Where扩展方法过滤返回的结果:

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

var tmpA = CorrectSelections.Where(opt => opt.Selected = true);
Run Code Online (Sandbox Code Playgroud)

当我实现tmpA时,会发生两件事:

  1. SOURCE列表中的数据发生变化 - 例如Red = True,Green = True,Blue = True
  2. tmpA中的数据设置为源列表已更改为的相同错误数据

有任何想法吗?

Ali*_*tad 14

你需要使用==而不是=:

var tmpA = CorrectSelections.Where(opt => opt.Selected == true);
Run Code Online (Sandbox Code Playgroud)

因此,当您搜索条件时,您正在设置值.这是一个常见的错误,我也属于它:)


Sco*_* M. 7

你的路线

opt => opt.Selected = true
Run Code Online (Sandbox Code Playgroud)

需要另一个等号:

opt => opt.Selected == true
Run Code Online (Sandbox Code Playgroud)