0

I have a list with nested items and I want to move values/node from Category1 to Category2 which are at same level. Doing it using a double for loop takes lot of time. How can I simplify and make it fast using LINQ?

foreach (var item in masterlist) {
    foreach (var item1 in item.Category1) {
        item1.Category1 = item1.Category2;
        item1.Category2 = null;
    }
}
2
  • 3
    LINQ won't make this any faster. It could make it shorter in terms of source code, but it won't make it any more efficient. (At least assuming this is in-memory, which I assume is the case here.) Commented Jun 13, 2019 at 13:35
  • Possible duplicate of Convert Nested Foreach to Linq Commented Jun 13, 2019 at 17:41

1 Answer 1

1

You still need to use a foreach because Linq is only concerned with iteration and querying and should not be used to introduce side-effects or actions (this is why Linq doesn't have a ForEach or Do extension method).

Note that because item.Category1 is overrwritten inside the loop you need to eagerly-evaluate the Linq expression first.

Try this (assuming your list-item type is named ListItem):

List<ListItem> allListItems = masterList
    .SelectMany( li => li.Category1 )
    .ToList();

foreach( ListItem item in listItems )
{
    item.Category1 = item.Category2;
    item.Category2 = null;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.