CSharp · Console
using System;
using System.Collections.Generic;
using static Fn;
public class Program
{
public static void Main()
{
var shapes = new List<Shape> {
new Shape { ShapeType = ShapeType.Circle },
new Shape { ShapeType = ShapeType.Square },
new Shape { ShapeType = ShapeType.Triangle },
new Shape { ShapeType = ShapeType.Square },
new Shape { ShapeType = ShapeType.Hexagon }
};
Func<Shape, bool> predicate = isSquare;
IEnumerable<Shape> squares = filter (shapes, predicate);
foreach(var square in squares) Console.WriteLine(square);
}
public static bool isSquare(Shape item) => item.ShapeType == ShapeType.Square;
}
public enum ShapeType
{
Triangle,
Square,
Circle,
Hexagon
}
public struct Shape
{
public ShapeType ShapeType;
public override string ToString(){
return $"I am a {ShapeType}.";
}
}
public static class Fn
{
public static IEnumerable<T> filter<T>(IEnumerable<T> collection, Func<T, bool> predicate)
{
foreach (var element in collection)
if (predicate(element))
yield return element;
}
public static IEnumerable<T> filter<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
foreach (var element in collection)
if (predicate(element))
yield return element;
}
}