加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Custom Inclusive TakeWhile(),还有更好的方法吗?

发布时间:2020-12-15 23:55:34 所属栏目:百科 来源:网络整理
导读:我编写了一个自定义LINQ扩展方法,它将TakeWhile()方法扩展为包含,而不是在谓词为false时将其排除. public static IEnumerableT TakeWhileT(this IEnumerableT source,FuncT,bool predicate,bool inclusive) { source.ThrowIfNull("source"); predicate.Throw
我编写了一个自定义LINQ扩展方法,它将TakeWhile()方法扩展为包含,而不是在谓词为false时将其排除.

public static IEnumerable<T> TakeWhile<T>(this IEnumerable<T> source,Func<T,bool> predicate,bool inclusive)
        {
            source.ThrowIfNull("source");
            predicate.ThrowIfNull("predicate");

            if (!inclusive)
                return source.TakeWhile(predicate);

            var totalCount = source.Count();
            var count = source.TakeWhile(predicate).Count();

            if (count == totalCount)
                return source;
            else
                return source.Take(count + 1);
        }

虽然这有效,但我确信有更好的方法.我很确定这在延迟执行/加载方面不起作用.

ThrowIfNull()是ArgumentNullException检查的扩展方法

社区可以提供一些提示或重写吗?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读