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;
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 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.) – Jon Skeet Jun 13 '19 at 13:35
  • Possible duplicate of [Convert Nested Foreach to Linq](https://stackoverflow.com/questions/18340405/convert-nested-foreach-to-linq) – Josh E Jun 13 '19 at 17:41

1 Answers1

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;
}
Dai
  • 141,631
  • 28
  • 261
  • 374