Home   Cover Cover Cover Cover
 

Erweiterungsmethode Where

A02.cs
/* Selecting elements from a sequence
   This example reimplements the method Where from class
   System.Linq.Enumerable and applies it to an array of integers
   and to an array of points.
------------------------------------------------------------*/
using System;
using System.Collections.Generic;


// static class with an extension method Where, which can be applied to
// IEnumerable< T >
static class Util {
  
  public static IEnumerable< T > Where< T >(this IEnumerable sequence, Func< T, bool> matches) {
    foreach (T elem in sequence) {
      if (matches(elem)) yield return elem;
    }
  }
}


struct Point {
  public int x ,y;
  public Point(int x, int y) { this.x = x; this.y = y; }
}


public class A2 {
  
  public static void Main() {
    //-- Selecting all even numbers
    int[] numbers = {1, 2, 3, 4 ,5, 6, 7, 8, 9, 10};
    Console.Write("Even numbers from ");
    foreach (int i in numbers) Console.Write(i + " ");
    Console.WriteLine();
    Console.Write("=> ");
    
    var result1 = numbers.Where(x => x % 2 == 0);
    foreach (int i in result1) Console.Write(i + " ");
    Console.WriteLine();
    Console.WriteLine();
    
    //-- Selecting all points in the upper right quadrant
    List points = new List {
      new Point(1, 2),
      new Point(-1, 2),
      new Point(3, -1),
      new Point(4, 2)
    };
    foreach (Point p in points) Console.Write("({0},{1}) ", p.x, p.y);
    Console.WriteLine();
    Console.Write("Points in upper right quadrant: ");
    
    var result2 = points.Where(p => p.x >= 0 && p.y >= 0);
    foreach (Point p in result2) Console.Write("({0},{1}) ", p.x, p.y);
    Console.WriteLine();
  }
}