LINQ的表达,而不是嵌套的foreach循环 [英] LINQ expression instead of nested foreach loops

查看:363
本文介绍了LINQ的表达,而不是嵌套的foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个clases:

 公共类客户{
公开名单<地址> AddressList中获得{;设置;}
}

公共类地址{
公共字符串名称{;组; }
}

和我有键入客户端<的List / code>名为 testList 。它包含N个客户端以及各包含n个地址

 列表<客户> testList; 



我如何能做到以下使用LINQ:

 的foreach(在testList VAR元素)
{
的foreach(VAR加入element.addressList)
{
console.writeLine( add.name);
}
}


解决方案

好我不会把 Console.WriteLine 在lambda表达式,但您可以使用的SelectMany 来避免嵌套:

 的foreach(在testList.SelectMany VAR增加(X => x.addressList))
{
Console.WriteLine(add.name);
}



我看不出有什么理由将结果转换到一个列表,然后使用列表< T> .ForEach 时,有一个非常好的的foreach 循环作为语言的一部分。它不象你自然的有无的委托适用于每一个名字,例如作为方法参数 - 你永远只是写到控制台。查看更多话题 埃里克利珀的博客文章想法。



(我也强烈建议你开始下面的.NET命名约定,但是这是一个不同的问题。)


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

这篇关于LINQ的表达,而不是嵌套的foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆