Skip to content

Instantly share code, notes, and snippets.

@kolosovpetro
Last active April 4, 2021 21:23
Show Gist options
  • Save kolosovpetro/67637e780bd43208a7fb34842bad2d2c to your computer and use it in GitHub Desktop.
Save kolosovpetro/67637e780bd43208a7fb34842bad2d2c to your computer and use it in GitHub Desktop.
FluentFilter.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Fluent
{
public static class Program
{
public static void Main()
{
var item = new Item(20);
item.AddFilter(x =>
{
Console.WriteLine("Item is between 0, 10");
return x.Value >= 0 && x.Value <= 10;
});
item.AddFilter(x =>
{
Console.WriteLine("Item is between 11, 20");
return x.Value >= 11 && x.Value <= 20;
});
item.AddFilter(x =>
{
Console.WriteLine("Item is between 21, 30");
return x.Value >= 21 && x.Value <= 30;
});
item.AddFilter(x =>
{
Console.WriteLine("Item is between 31, 40");
return x.Value >= 31 && x.Value <= 40;
});
item.Compile();
}
}
public class Item
{
private readonly List<Func<Item, bool>> _delegates = new List<Func<Item, bool>>();
public int Value { get; }
public Item()
{
Value = new Random().Next(0, 100);
}
public Item(int value)
{
Value = value;
}
public Item AddFilter(Func<Item, bool> filter)
{
_delegates.Add(filter);
return this;
}
public void Compile()
{
var valid = _delegates.First(x => x(this));
Console.Clear();
valid.Invoke(this);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment