0

I have collection which have other collection in it. And I need some elegant solution to the following:

I need to filter the first collection by it is inner collection. So in the first collection will remain only the objects that have nested collection which answer some filter. Next i want in the filtered first object to have inner collection filtered by the same filter.

Check the first level filtering:

collectionOne = collectionOne.Where(a => a.collectionTwo.Any(g => !string.IsNullOrEmpty(g.Value) && g.Value.Contains(stringValue)));

This way i will filter the first collection, but the inner one will be still not filtered. I want to filter the inner collection with the same filter for each object in the first one :) I can do this with some loop (afte the first filter), but maybe there is better way?

Possible solution:

foreach(var item in collectionOne)
{
  item.collectionTwo = ... same filter
}

P.S. The reason I ask this is because there is also a switch case about the filter itself. So I will have to copy-paste the solution a couple times with different filter only. That` why i do not prefer the loop.

Other Solution is to create Func which will be re-used in .Where clause, but this is also not efficient because each filter is kind of simple.

Jackie
  • 327
  • 2
  • 13
  • [Check this SO topic](https://stackoverflow.com/questions/1590723/flatten-list-in-linq) or you may also try to create extension method. First option will require creating additional copy of the list, maybe recreating it. If it is always 2-level list, I'd really go for filtering in a loop. Keep it simple. – Mike Sar Jul 29 '19 at 09:31

1 Answers1

3

If understand it correctly, what you're looking for is:

collectionOne = collectionOne
                    .Where(filter)
                    .Select(item =>
                        {
                            item.collectionTwo = collectionTwo.Where(filter);
                            return item;
                        });

And, if you just want to select and not modify the items:

collectionOne = collectionOne
                    .Where(filter)
                    .Select(item =>
                        new X{
                            collectionTwo = collectionTwo.Where(filter),
                            // copy all other fields
                        });
Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59