Me5
Me5

Reputation: 1885

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?

Upvotes: 1

Views: 1209

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

You also could use query language if that looks "simpler" to you:

List<string> wantedList = (from person in personList where person.IsMarried
                           from child in person.Children where child.Greater5 
                           from color in child.ListColor where !string.IsNullOrEmpty(color.Type)
                           select color.Type).ToList();

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460028

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)))
    .ToList();

Upvotes: 2

Related Questions