I have these two clases:
public class Client{
public List<Address> addressList{get;set;}
}
public class Address{
public string name { get; set; }
}
and I have a List of type Client
called testList
. It contains n clients and each one of those contains n addresses
List<Client> testList;
how can i do the following using LINQ:
foreach (var element in testList)
{
foreach (var add in element.addressList)
{
console.writeLine(add.name);
}
}
Well I wouldn't put the Console.WriteLine
in a lambda expression, but you can use SelectMany
to avoid the nesting:
foreach (var add in testList.SelectMany(x => x.addressList))
{
Console.WriteLine(add.name);
}
I see little reason to convert the results to a list and then use List<T>.ForEach
when there's a perfectly good foreach
loop as part of the language. It's not like you naturally have a delegate to apply to each name, e.g. as a method parameter - you're always just writing to the console. See Eric Lippert's blog post on the topic for more thoughts.
(I'd also strongly recommend that you start following .NET naming conventions, but that's a different matter.)
See more on this question at Stackoverflow