简体   繁体   English

使用Linq更新列表

[英]Updating a list using Linq

I am creating two lists of objects. 我正在创建两个对象列表。 One "new" list, one "old list". 一个“新”列表,一个“旧列表”。

I want to take the value of one property from an object on the new list and set the property on the old list on the matching object the the new value. 我想从新列表上的对象中获取一个属性的值,并在匹配对象的旧列表上将属性设置为新值。

//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;
                }
            }
        }

I am trying to convert it to LINQ to make it more effecient using joins, but how do i update the value directly? 我正在尝试将其转换为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;

This query returns the values to the x list, but I want to actually update the object in the old list instead. 该查询将值返回到x列表,但是我实际上想更新旧列表中的对象。

Linq is for querying , not updating . Linq用于查询 ,而不用于更新 You can join the two lists to line up the object to update, but you'll still have to loop to make the changes: 您可以将两个列表连接起来以排队更新对象,但是仍然需要循环进行更改:

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

For example: 例如:

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;
}

You mean this? 你是这个意思?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM