可以将其重构为漂亮的LINQ吗? [英] Can this be refactored into nicey nice LINQ?

查看:49
本文介绍了可以将其重构为漂亮的LINQ吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类型为Breadcrumb的IList,它只是一个具有NavigationTitle,NavigationUrl和IsCurrent属性的轻量级类.它被缓存在Web服务器上.我有一种方法,使用下面的代码来构建当前的面包屑轨迹,直到第一个将IsCurrent设置为true的面包屑为止.它非常丑陋,而且绝对是一种快速的垃圾袋威利解决方案,但是我很好奇,这可以很容易地重构为LINQ吗?

I have an IList of type Breadcrumb which is just a lightweight class that has NavigationTitle, NavigationUrl and IsCurrent properties. It is cached on the webserver. I have a method that builds out the current breadcrumb trail up until the first Breadcrumb that has IsCurrent set to true... using the code below. Its very ugly and definitely a quick dirtbag willie solution, but I was curious, can this be easily refactored into LINQ?

IList<Breadcrumb> crumbs = new List<Breadcrumb>();
bool foundCurrent = false;
for (int a = 0; a < cachedCrumbs.Count; a++)
{
    crumbs.Add(crumbs[a]);
    if (foundCurrent)
    {
      break;
    }
    foundCurrent = (crumbs[a + 1] != null && ((Breadcrumb)crumbs[a + 1]).IsCurrent);
}

推荐答案

我正在输入我认为的内容,因此它不仅显示了思路,而且还给出了答案.

I'm typing this as I think, so that it shows a train of thought as well as just an answer.

  • 您的来源只是cachedCrumbs
  • 您要添加设置有IsCurrent的第一个面包屑,但此后什么都没有
  • TakeWhile听起来很可行,但是要获得以前的值具有IsCurrent"有点痛苦
  • 我们可以使用闭包有效地保留一个变量,以确定最后一个值是否设置了IsCurrent
  • 我们可以进行一些无操作"选择,以使TakeWhile与是否继续运行分开进行

所以,我们最终得到:

bool foundCurrent = false;

var crumbs = cachedCrumbs.TakeWhile(crumb => !foundCurrent)
                         .Select(crumb => { 
                                 foundCurrent = crumb == null || !crumb.IsCurrent; 
                                 return crumb; });

我还没有尝试过,但是我认为应该可以工作……不过,也许有一种更简单的方法.

I haven't tried this, but I think it should work... there might be a simpler way though.

我认为在这种情况下,一个简单的foreach循环 更为简单.话虽如此,您可以编写另一个与TakeWhile相似的扩展方法,除了它返回导致条件失败的元素.然后就这么简单:

I'd argue that actually a straight foreach loop is simpler in this case. Having said that, you could write another extension method which acted like TakeWhile except it also returned the element which caused the condition to fail. Then it would be as simple as:

var crumbs = cachedCrumbs.NewMethod(crumb => crumb == null || !crumb.IsCurrent);

(目前我无法想到该方法的一个体面的名称,因此NewMethod!)

(I can't think of a decent name for the method at the moment, hence NewMethod !)

这篇关于可以将其重构为漂亮的LINQ吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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