不同的看法上FirstOrDefault [英] A different take on FirstOrDefault

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

问题描述

了IEnumerable扩展方法FirstOrDefault并没有完全做到,因为我想,所以我创建FirstOrValue。这是一个很好的方式去这还是有一个更好的办法

 公共静态牛逼FirstOrValue< T>(这个IEnumerable的< ; T>源,Func键< T,BOOL>谓语,T值)
{$ b $(b T)=第一source.FirstOrDefault(谓语);
收益等于(第一,默认(T))?价值:第一;
}


解决方案

您的代码可能不正确;你可能没有考虑所有的情况。



当然,我们不能知道任何代码是否正确或不正确的,直到我们有一个规范。因此,通过写一行规格启动:



FirstOrValue< T> 需要T的序列,谓词,和T的值,并返回要么谓词如果有一个,或者,如果没有,则所述值相匹配的序列中的第一项。



您是否尝试实际上实现该规范呢?当然不是!测试:

  INT X = FirstOrValue< INT>(新[] {-2,0,1},Y => ; Y * Y = = Y,-1); 

这将返回-1。根据规范正确答案是0匹配谓词为零的第一个项目,所以应该归还。



一个正确实施的规范将如下所示:

 公开静态ŧFirstOrValue< T>(这个IEnumerable的< T>序列,Func键< T,BOOL>谓语,T值)
{
如果(序列== NULL)抛出新的ArgumentNullException(序);
如果(谓词== NULL)抛出新的ArgumentNullException(上游);
的foreach(在顺序。T项)
如果(谓词(项目))回报项目;
返回值;
}



总是先写一个规范,哪怕它只是一个简单的句子。


The IEnumerable extension method FirstOrDefault didn't exactly do as I wanted so I created FirstOrValue. Is this a good way to go about this or is there a better way?

public static T FirstOrValue<T>(this IEnumerable<T> source, Func<T, bool> predicate, T value)
{
    T first = source.FirstOrDefault(predicate);
    return Equals(first, default(T)) ? value : first;
}

解决方案

Your code is probably incorrect; you probably haven't considered all of the cases.

Of course, we cannot know if any code is correct or incorrect until we have a spec. So start by writing a one-line spec:

"FirstOrValue<T> takes a sequence of T, a predicate, and a value of T, and returns either the first item in the sequence that matches the predicate if there is one, or, if there is not, the stated value."

Does your attempt actually implement that spec? Certainly not! Test it:

int x = FirstOrValue<int>( new[] { -2, 0, 1 }, y=>y*y==y, -1);

this returns -1. The correct answer according to the spec is 0. The first item that matches the predicate is zero, so it should be returned.

A correct implementation of the spec would look like:

public static T FirstOrValue<T>(this IEnumerable<T> sequence, Func<T, bool> predicate, T value)
{
    if (sequence == null) throw new ArgumentNullException("sequence");
    if (predicate == null) throw new ArgumentNullException("predicate");
    foreach(T item in sequence)
        if (predicate(item)) return item;
    return value;
}

Always write a spec first, even if it's only a single sentence.

这篇关于不同的看法上FirstOrDefault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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