处理可能多次枚举IEnumerable的警告

本文翻译自:Handling warning for possible multiple enumeration of IEnumerable

In my code in need to use an IEnumerable<> several times thus get the Resharper error of "Possible multiple enumeration of IEnumerable ". 在我的代码中需要使用IEnumerable<>几次因此得到Resharper错误“可能多次枚举IEnumerable ”。

Sample code: 示例代码:

public List<object> Foo(IEnumerable<object> objects)
{
    if (objects == null || !objects.Any())
        throw new ArgumentException();

    var firstObject = objects.First();
    var list = DoSomeThing(firstObject);        
    var secondList = DoSomeThingElse(objects);
    list.AddRange(secondList);

    return list;
}
  • I can change the objects parameter to be List and then avoid the possible multiple enumeration but then I don't get the highest object that I can handle. 我可以将objects参数更改为List ,然后避免可能的多次枚举,但后来我没有得到我能处理的最高对象。
  • Another thing that I can do is to convert the IEnumerable to List at the beginning of the method: 我能做的另一件事是在方法的开头将IEnumerable转换为List

 public List<object> Foo(IEnumerable<object> objects)
 {
    var objectList = objects.ToList();
    // ...
 }

But this is just awkward . 但这只是尴尬

What would you do in this scenario? 在这种情况下你会做什么?


#1楼

参考:https://stackoom.com/question/YZoq/处理可能多次枚举IEnumerable的警告


#2楼

I usually overload my method with IEnumerable and IList in this situation. 在这种情况下,我通常使用IEnumerable和IList重载我的方法。

public static IEnumerable<T> Method<T>( this IList<T> source ){... }

public static IEnumerable<T> M
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值