Home   Cover Cover Cover Cover
 

Iterieren über eine Liste

IterateList.cs
//==========================================================
// Iterating over a list
//==========================================================

using System;
using System.Collections.Generic;

//----------------------------------------------------------
// list nodes
//----------------------------------------------------------
class Node {
  public string val;
  public Node next;
  public Node(string s) { val = s; }
}
  
//----------------------------------------------------------
// linked list of strings
//----------------------------------------------------------
class List {
  Node head = null, tail = null;
  
  // adds a string to the end of the list
  public void Add(string s) {
    Node n = new Node(s);
    if (head == null) head = n; else tail.next = n;
    tail = n;
  }
  
  // general iterator over all strings in the list
  public IEnumerator<string> GetEnumerator() {
    for (Node n = head; n != null; n = n.next)
      yield return n.val;
  }
  
  // specific iterator yielding all strings that start with s
  public IEnumerable<string> ElementsStartingWith(string s) {
    for (Node n = head; n != null; n = n.next)
      if (n.val.StartsWith(s)) yield return n.val;
  }
  
  // iterator property yielding all strings longer than 5 characters
  public IEnumerable<string> LongStrings {
    get {
      for (Node n = head; n != null; n = n.next)
        if (n.val.Length > 5) yield return n.val;
    }
  }
}

//----------------------------------------------------------
// test program
//----------------------------------------------------------
class Test {
  
  public static void Main() {
    List list = new List();
    list.Add("Rome");
    list.Add("Vienna");
    list.Add("Linz");
    list.Add("Paris");
    list.Add("Berlin");
    list.Add("London");
    
    foreach (string s in list)
      Console.WriteLine(s);
    Console.WriteLine();
    
    foreach (string s in list.ElementsStartingWith("L"))
      Console.WriteLine(s);
    Console.WriteLine();
    
    foreach (string s in list.LongStrings)
      Console.WriteLine(s);
    Console.WriteLine();
  }
}