使用Linq更新列表

时间:2015-01-30 14:23:09

标签: c# linq

我正在创建两个对象列表。一个"新"列表,一个"旧列表"。

我想从新列表中的对象中获取一个属性的值,并将匹配对象上旧列表中的属性设置为新值。

//Original Solution
        foreach (RyderQuestion quest in myList)
        {
            //compare it to every question in ryder questions
            foreach (RyderQuestion oldQuestion in _ryderQuestions)
            {
                //if the question ids match, they are the same question, and should have the right selected option
                //selecting the option sets the checkbox of the MultipleChoideQuestionControl
                if (oldQuestion.QuestionID == quest.QuestionID)
                {
                    oldQuestion.SelectedOption = quest.SelectedOption;
                }
            }
        }

我正在尝试将其转换为LINQ以使其更有效地使用连接,但我如何直接更新值?

        var x = from quest in myList
                join oldquest in _ryderQuestions
                on new { quest.QuestionID, quest.ShowOn, quest.QuestionOrder }
            equals new { oldquest.QuestionID, oldquest.ShowOn, oldquest.QuestionOrder }
                select oldquest.SelectedOption = quest.SelectedOption;

此查询将值返回到x列表,但我想实际更新旧列表中的对象。

2 个答案:

答案 0 :(得分:3)

Linq用于查询,而非更新。您可以加入这两个列表来排列要更新的对象,但您仍然需要循环才能进行更改:

var query = from quest in myList
            join oldquest in _ryderQuestions
            on new { quest.QuestionID, quest.ShowOn, quest.QuestionOrder }
        equals new { oldquest.QuestionID, oldquest.ShowOn, oldquest.QuestionOrder }
            select new {oldquest, quest};

foreach(var item in query}
    item.oldquest.SelectedOption = item.quest.SelectedOption

答案 1 :(得分:2)

例如:

var x = from quest in myList
            join oldquest in _ryderQuestions
            on new { quest.QuestionID, quest.ShowOn, quest.QuestionOrder }
        equals new { oldquest.QuestionID, oldquest.ShowOn, oldquest.QuestionOrder }

            select new {quest , oldquest};

foreach(var item in x)
{
    item.quest.SelectedOption = item.oldquest.SelectedOption;
}

你是说这个?