简体   繁体   中英

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?

        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.

Linq is for querying , not updating . 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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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