小编Ste*_*fan的帖子

自定义Linq扩展的性能差异/改进

首先,我不确定这个问题是否适合这个社区.如果没有请告诉我在哪里移动它:)

所以,我经常发现自己经常写这样的Linq表达式:

var xy = someSource.Where(x => x.Property == value).Select(x => new Y(x));
Run Code Online (Sandbox Code Playgroud)

在重构我的代码时,我认为这实际上枚举了我的源代码两次,所以我写了这个小扩展(实际上没什么特别的):

    public static IEnumerable<TResult> SelectWhere<TIn, TResult>(this IEnumerable<TIn> source,
        Func<TIn, bool> predicate, Func<TIn, TResult> selector)
    {
        foreach (var item in source)
        {
            if (predicate(item))
            {
                yield return selector(item);
            }
        }
    } 
Run Code Online (Sandbox Code Playgroud)

所以我可以用我的查询替换

var xy = someSource.SelectWhere(x => x.Property == value, x => new Y(x));
Run Code Online (Sandbox Code Playgroud)

当然,这只会有明显的性能提升(如果它确实存在),如果源可枚举大或每个"移动下一个"需要很长时间.

我的问题是:这是否真的提高了性能(一点点),是否值得进行此扩展?

c# linq performance

3
推荐指数
1
解决办法
217
查看次数

标签 统计

c# ×1

linq ×1

performance ×1