LINQ + VS Foreach源Foreach源+如果 [英] LINQ + Foreach vs Foreach + If

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

问题描述

我需要遍历对象的名单,只为有一个布尔属性设置为true的对象做一些事情。我这个code之争

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 }

这code

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

第一code显然是更清洁,但我怀疑它会遍历所有的列表两次 - 一次查询,并一度对foreach。这会不会是一个巨大的名单,所以我不是太关心性能,但两次循环的想法只是错误的我。

问:是否有一个干净/ pretty的方式来写这个不用循环两次

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

推荐答案

乔恩斯基特有时做一个真人演示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版和继续的版本是一样的;如果你有

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 + VS Foreach源Foreach源+如果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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