LINQ + Foreach 与 Foreach + If [英] LINQ + Foreach vs Foreach + If

查看:20
本文介绍了LINQ + Foreach 与 Foreach + If的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历对象列表,只对布尔属性设置为 true 的对象执行某些操作.我正在争论这段代码

I need to iterate over a List of objects, doing something only for the objects that have a boolean property set to true. I'm debating between this code

foreach (RouteParameter parameter in parameters.Where(p => p.Condition))
{ //do something }

和这段代码

foreach (RouteParameter parameter in parameters)
{ 
  if !parameter.Condition
    continue;
  //do something
}

第一个代码显然更简洁,但我怀疑它会遍历列表两次 - 一次用于查询,一次用于 foreach.这不会是一个很大的列表,所以我并不太关心性能,但是循环两次的想法只会错误我.

The first code is obviously cleaner, but I suspect it's going to loop over the list twice - once for the query and once for the foreach. This won't be a huge list so I'm not overly concerned about performance, but the idea of looping twice just bugs me.

问题:有没有一种干净/漂亮的方式来编写它而不需要循环两次?

Question: Is there a clean/pretty way to write this without looping twice?

推荐答案

Jon Skeet 有时会做一个真人 LINQ 演示来解释这是如何工作的.想象一下,你在舞台上有三个人.在左边我们有一个人,他有一副洗好的牌.在中间,我们有一个只会传红牌的人,而在右边,我们有一个想要红牌的人.

Jon Skeet sometimes does a live-action LINQ demo to explain how this works. Imagine you have three people on stage. On the left we have one guy who has a shuffled deck of cards. In the middle we have one guy who only passes along red cards, and on the right, we have a guy who wants cards.

右边的人戳了中间的人.中间的人戳左边的人.左边的人给中间的人一张牌.如果是黑色,中间的人将它扔在地板上并再次戳,直到他得到一张红牌,然后他将红牌交给右边的人.然后右边的家伙又戳了中间的家伙.

The guy on the right pokes the guy in the middle. The guy in the middle pokes the guy on the left. The guy on the left hands the guy in the middle a card. If it is black, the guy in the middle throws it on the floor and pokes again until he gets a red card, which he then hands to the guy on the right. Then the guy on the right pokes the guy in the middle again.

这种情况一直持续到左边的人用完牌.

This continues until the guy on the left runs out of cards.

一副牌从头到尾经过不止一次.然而,左边的人和中间的人处理了 52 张牌,右边的人处理了 26 张牌牌.总共对卡片进行了 52 + 52 + 26 次操作,但是一副牌只循环了一次.

The deck was not gone through from start to finish more than once. However, both the guy on the left and the guy in the middle handled 52 cards, and the guy on the right handled 26 cards. There were a total of 52 + 52 + 26 operations on cards, but the deck was only looped through once.

你的LINQ"版本和continue"版本是一样的;如果你有

Your "LINQ" version and the "continue" version are the same thing; if you had

foreach(var card in deck)
{
    if (card.IsBlack) continue;
    ... use card ...

然后有 52 个操作从一副牌中取出每张卡片,52 个操作测试每张卡片是否为黑色,以及 26 个操作对红色卡片起作用.完全一样.

then there are 52 operations that fetch each card from the deck, 52 operations that test to see if each card is black, and 26 operations that act on the red card. Same thing exactly.

这篇关于LINQ + Foreach 与 Foreach + If的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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