|
|
Erweiterungsmethode Collect
A03.cs
/* Transforming a sequence
This example implements an extension method Collect, which transforms
a sequence of type IEnumerable< T > into a sequence of the same type,
using a lambda expression to specify the transformation of every element.
------------------------------------------------------------*/
using System;
using System.Collections.Generic;
// static class with an extension method Collect, which can be applied to
// IEnumerable< T >
static class Util {
public static IEnumerable< T > Collect< T >(this IEnumerable< T > sequence, Func< T, T > transform) {
foreach (T elem in sequence) {
yield return transform(elem);
}
}
}
public class A3 {
public static void Main() {
//-- Squares of integers
int[] numbers = {1, 2, 3, 4 ,5, 6, 7, 8, 9, 10};
Console.Write("Squares of ");
foreach (int i in numbers) Console.Write(i + " ");
Console.WriteLine();
Console.Write("=> ");
var result1 = numbers.Collect(x => x * x);
foreach (int i in result1) Console.Write(i + " ");
Console.WriteLine();
Console.WriteLine();
//-- Caesar cipher (message in lower case letters)
string msg = "a secret message";
Console.WriteLine("Message: " + msg);
Console.Write("Encrypted: ");
var result2 = msg.Collect(ch => {
if ('a' <= ch && ch <= 'z') {
return (char) ('a' + ((ch - 'a') + 3) % 26); // move every letter by 3 positions
} else {
return ch;
}
});
foreach (char ch in result2) Console.Write(ch);
Console.WriteLine();
}
}
|
|