将嵌套的 foreach 转换为 lambda 表达式
我想将嵌套的 foreach 转换
foreach (Tuple<int, string, Guid> s in services)
{
foreach (BEPartnership p in partnership)
{
p.Partner.Services = new List<Tuple<int, string>>();
if (s.Item3 == p.Partner.Id)
p.Partner.Services.Add(new Tuple<int, string>(s.Item1, s.Item2));
}
}
为这样的东西
services.SelectMany(
s=>partnership.Select(
p=>new {partnerId = p.Partner.Id, servicePartnerId = s.Item3})
.Where(x=>x.partnerId == x.servicePartnerId)
.ToList()
.ForEach( //....) )
I want to convert nested foreach
foreach (Tuple<int, string, Guid> s in services)
{
foreach (BEPartnership p in partnership)
{
p.Partner.Services = new List<Tuple<int, string>>();
if (s.Item3 == p.Partner.Id)
p.Partner.Services.Add(new Tuple<int, string>(s.Item1, s.Item2));
}
}
to something like this
services.SelectMany(
s=>partnership.Select(
p=>new {partnerId = p.Partner.Id, servicePartnerId = s.Item3})
.Where(x=>x.partnerId == x.servicePartnerId)
.ToList()
.ForEach( //....) )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以安装 ReSharper 5 的试用版,因为它有一个重构选项,可以将(如果可能)
foreach
循环转换为 LINQ 表达式。http://blogs.jetbrains.com/ dotnet/2009/12/resharper-50-preview-loops-2-linq/
You could install the trial version of ReSharper 5, as this has a refactor option that will convert (if possible) a
foreach
loop into a LINQ expression.http://blogs.jetbrains.com/dotnet/2009/12/resharper-50-preview-loops-2-linq/
您实际上并没有在这里进行查询,因此 LINQ 可能是错误的方法。
但是,您可以将两个 foreach 循环更改为:
这真的有什么好处吗?我对此表示怀疑。
继续使用 SelectMany 之类的东西感觉就像强奸 LINQ,所以我停在这里。
You are not really doing a query here, so LINQ might be the wrong approach.
However, you can change your two foreach loops to this:
Does this really provides any benefit? I doubt it.
Going any further with SelectMany and stuff feels like raping LINQ, so I stopped here.
首先,我总是创建一个静态实用程序/扩展类来定义这些方法:
现在您需要的是:
First, I always create a static utility/extension class to define these methods:
Now all you need is this: