Skip to content

Instantly share code, notes, and snippets.

@albertein
Created December 17, 2010 00:32
Show Gist options
  • Save albertein/744285 to your computer and use it in GitHub Desktop.
Save albertein/744285 to your computer and use it in GitHub Desktop.
Using reflection + delegates to dinamically filter IEnumerable<T>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var dudes = new List<Empleado>
{
new Empleado {Nombre = "Alberto", Edad = 25},
new Empleado {Nombre = "1Alberto", Edad = 30},
new Empleado {Nombre = "21Alberto", Edad = 18},
new Empleado {Nombre = "3Alberto", Edad = 16},
};
var printer = new Action<Empleado> ( x => Console.WriteLine("{0} - {1}", x.Nombre, x.Edad) );
var data = dudes.FilterContains("Nombre", "1").FilterGreaterThan("Edad", 20);
foreach (var item in data)
printer(item);
}
}
class Empleado
{
public string Nombre { get; set; }
public int Edad { get; set; }
}
public static class Filtertron2000
{
public static IEnumerable<T> FilterEqual<T>(this IEnumerable<T> data, string field, object value)
{
var type = typeof(T);
return Filter(data,
x => type.GetProperty(field).GetValue(x, null).Equals(value));
}
public static IEnumerable<T> FilterContains<T>(this IEnumerable<T> data, string field, string value)
{
var type = typeof(T);
return Filter(data,
x => (type.GetProperty(field).GetValue(x, null) as string).Contains(value));
}
public static IEnumerable<T> FilterGreaterThan<T>(this IEnumerable<T> data, string field, int value)
{
var type = typeof(T);
return Filter(data,
x => ((int)(type.GetProperty(field).GetValue(x, null))) > value);
}
public static IEnumerable<T> FilterLessThan<T>(this IEnumerable<T> data, string field, int value)
{
var type = typeof(T);
return Filter(data,
x => ((int)(type.GetProperty(field).GetValue(x, null))) > value);
}
static IEnumerable<T> Filter<T>(IEnumerable<T> data, Func<T, bool> predicate)
{
var type = typeof(T);
foreach (var item in data)
{
if (predicate(item))
yield return item;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment