Me5 Me5 -4 years ago 95
C# Question

How to get list<string> from list of list of list linq C#

I have the classes:

public class Person
public string Name{get;set;}
public bool IsMarried{get;set;}
public List<Child> Children { get; set; }
public class Child
public bool Greater5 { get; set; }
public List<MyColor> ListColor { get; set; }
public class MyColor
public string History { get; set; }
public string Type { get; set; }

I want to obtain a list string (MyColor.Type which are not empty) for all persons where IsMarried=true and Children.Greater5 = true.
I can achieve this with:

List<Person> list = personList.Where(l => l.IsMarried == true).ToList();
List<Child> childList = list.SelectMany(c => c.Children).Where(test => test.Greater5 == true).ToList();
List<string> wantedList= childList.SelectMany(test => test.ListColor.Where(c => !String.IsNullOrEmpty(c.Type)).Select(t => t.Type)).ToList();

but I was wondering if it could be achieved using Linq to be more simpler?

Answer Source

You can chain SelectMany to flatten nested children.

List<string> wantedList = personList
    .Where(person => person.IsMarried)
    .SelectMany(person => person.Children
        .Where(child => child.Greater5)
        .SelectMany(child => child.ListColor
            .Where(color => !String.IsNullOrEmpty(color.Type))
            .Select(color => color.Type)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download