Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - LINQ expression instead of nested foreach loops

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);
    }
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...