Alice
Alice

Reputation: 45

Using LINQ in lists for creating new lists

I have such a code and I want to select all people's name using LINQ and print new list.

var dataGroups = new List<Group>
{
    new Group { Manager = "Bob Brown", Task= " Backend", Developers = new List<Developer>() {
        new Developer { Name = "Nikolas Johns", Birthdate = new DateTime(1973, 4, 22)},
        new Developer { Name = "Robert Green", Birthdate = new DateTime(1989, 12, 11)},
        new Developer { Name = "Mary Williams", Birthdate = new DateTime(1996, 3, 10)}
    }},
    new Group { Manager = "Vanessa May", Task = "Frontend", Developers = new List<Developer>() {
        new Developer { Name = "Dao Li", Birthdate = new DateTime(2000, 3, 15)},
        new Developer{ Name = "Zara Kavarska", Birthdate = new DateTime(1981, 6, 19)},
    }},
};
         

I use something like this and I don't get desired result.

var devNames = dataGroups.Select(group => group.Developers.Select(developer => developer.Name));
foreach(var name in devNames)
{
    Console.Write(name + "  ");
}

Do you know how to tackle this problem? I’m very new to the subject, I’d be grateful for your help.

Upvotes: 0

Views: 122

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460208

You use SelectMany if you want to project inner sequences and flatten them:

IEnumerable<string> devNames = dataGroups
    .SelectMany(group => group.Developers.Select(developer => developer.Name));

Upvotes: 4

Related Questions