Skip to content

Iterators and Enumerables

TypeScript iterators map to C# Enumerable / IEnumerable. These abstractions provide forward, read-only semantics.

Most generally, they represent a forward-only "virtual" iteration over a set.

Working with Iterators and Enumerables

ts
let nameToAge = new Map<string, number>([
  ["Anne", 12],
  ["Bert", 23],
  ["Carl", 43],
]);

// Enumerate
for (const entry of nameToAge.values()) {
    console.log(entry) // 12, 23, 43
}

// Convert to array
let ages = Array.from(nameToAge.values());
csharp
var nameToAge = new OrderedDictionary<string, int> {
  ["Anne"] = 12,
  ["Bert"] = 23,
  ["Carl"] = 43,
};

// Enumerate
foreach (var entry in nameToAge.Values) {
  Console.WriteLine(entry) // 12, 23, 43
}

// Convert to List<T> (T is inferred automatically)
var ages = nameToAge.Values.ToList();

In Generators and Yield, we'll explore how to use generator functions and the common yield statement to produce a stream of results.