没有foreach循环使用的IEnumerable [英] Using IEnumerable without foreach loop

查看:123
本文介绍了没有foreach循环使用的IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得失去了一些东西在这里简单



看看下面的代码:

 公开的IEnumerable< INT>调用getInt(){
的for(int i = 0;我小于10;我++){$​​ B $ B收益回报我;

$:
}
}



我可以把这个b
$ b

 的foreach(在obj.getInt诠释J()){
//做其中j
的东西}

我如何使用getInt方法不foreach循环:

 的IEnumerable< INT> ITER = obj.getInt(); 
//做一些国际热核实验堆?



感谢。



EDITS



对于那些想知道我为什么会想这个。我迭代两件事情:

 的IEnumerator< INT> ITER = obj.getInt()的GetEnumerator()。 
的foreach(在XS对象x){
如果(x.someCondition)继续;
iter.MoveNext();
INT N = iter.current();
x.someProp = N;
等...
}


解决方案

您可以获取到枚举参考,使用的 的GetEnumerator 方法,那么您可以使用的 的MoveNext 方法继续前进,并使用电流属性来访问你的元素:

  VAR枚举=调用getInt()的GetEnumerator(); 
,而(enumerator.MoveNext())
{
INT N = enumerator.Current;
Console.WriteLine(N);
}


I've gotta be missing something simple here.

Take the following code:

public IEnumerable<int> getInt(){
  for(int i = 0; i < 10; i++){
   yield return i;
  }
}

I can call this with:

foreach (int j in obj.getInt()){
  //do something with j
}

How can I use the getInt method without the foreach loop:

IEnumerable<int> iter = obj.getInt();
// do something with iter ??

Thanks.

EDITS

For those wondering why I'd want this. I'm iterating two things:

IEnumerator<int> iter = obj.getInt().GetEnumerator();
foreach(object x in xs){
  if (x.someCondition) continue;
  iter.MoveNext();
  int n = iter.current();
  x.someProp = n;
  etc...
}

解决方案

You can get a reference to the Enumerator, using the GetEnumerator method, then you can use the MoveNext method to move on, and use the Current property to access your elements:

var enumerator = getInt().GetEnumerator();
while(enumerator.MoveNext())
{
    int n = enumerator.Current;
    Console.WriteLine(n);
}

这篇关于没有foreach循环使用的IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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