Is it possible to have multiple iterators in C #?

Is it possible to use multiple iterators (for one class or object) in C # .net? If this gives me some simple examples. Sorry if the question is not clear and please let me know.

+1
source share
3 answers

You could create different iterators for passing in different ways. For example, you could:

public class Tree<T> { public IEnumerable<T> IterateDepthFirst() { // Iterate, using yield return ... } public IEnumerable<T> IterateBreadthFirst() { // Iterate, using yield return ... } } 

Is that what you asked?

You can also write:

 public class Foo : IEnumerable<int>, IEnumerable<string> 

but this will cause a lot of confusion, and the foreach will pick the one that had the implicitly implemented call to GetEnumerator .

You can also repeat several times over the same collection:

 foreach (Person person1 in party) { foreach (Person person2 in party) { if (person1 != person2) { person1.SayHello(person2); } } } 
+6
source

It's not entirely clear if you mean that you can implement more than one iterator for a class, or if you can use more than one iterator for a class at a time. Also possible.

You can have as many iterators as you like for the class:

 public class OddEvenList<T> : List<T> { public IEnumerable<T> GetOddEnumerator() { return this.Where((x, i) => i % 2 == 0); } public IEnumerable<T> GetEvenEnumerator() { return this.Where((x, i) => i % 2 == 1); } } 

You can have as many iterator instances for the active class at one time as you like:

 foreach (int x in list) { foreach (int y in list) { foreach (int z in list) { ... } } } 
+1
source

One option would be to implement a strategy template:

  • Create separate IEnumerator classes for each crawl strategy.
  • Create a private attribute in the collection that stores the current strategy (with a default value).
  • Create a SetStrategy method that changes this private attribute to the selected specific strategy.
  • Replace GetEnumerator to return an instance of the current strategy.

Of course, this means that two threads trying to establish a strategy at the same time can interfere, so if sharing a collection between threads is important, this is not the best solution.

The direct iterator template will also work, which I assume Jon Skeet offers in his first example, but you lose syntactic sugar that can use foreach.

0
source

Source: https://habr.com/ru/post/1304063/


All Articles