0

I have a list which also contains a list which contains some objects:

var elements = new List<ElementGroup>()
            {
                new ElementGroup("WIRES")
                {
                    new Element() {Name = "Wires", Image = "wires.jpg"}
                },
                new ElementGroup("GROUND")
                {
                    new Element() {Name = "Ground", Image = "ground.jpg"}
                }
            };

ElementGroup class:

public class ElementGroup : List<Element>

I want to apply Linq query to all Element objects from all ElementGroup lists but if I do it like this:

elements.Where(c => c.Family.Contains(searchText.ToUpper()));

it applies the query on ElementGroup lists.

2 Answers2

0
//Here is how you can get List of Element from List<ElementGroup>.

List<Element> result = 
    elements.SelectMany(elementGroup =>             
        elementGroup.Where(element=>element.Name=="Wires")).ToList();
Yogee
  • 1,412
  • 14
  • 22
-1

Use SelectMany which flattens the inner list.

Code might look like this elements.SelectMany(s => s.Elements)

And you can work on this list of elements

EDIT:

Also, consider having a list of Elements "in" ElementGroup rather than inheriting. Then using SelectMany becomes the natural choice.

gtestasker
  • 61
  • 7
  • @Ionut Gabriel Pitigoi - Any specific reason you are inheriting and not having List as a property in ElementGroup? – gtestasker Mar 26 '18 at 14:59