Skip to content

Instantly share code, notes, and snippets.

@davecowart
Created April 10, 2010 06:00
Show Gist options
  • Save davecowart/361859 to your computer and use it in GitHub Desktop.
Save davecowart/361859 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
int? minValue = 5;
int? maxValue = 17;
string stringValue = "odd";
var searcher = new Search<SearchObject>(GenerateSearchObjects().AsQueryable());
searcher.RangeFilter(minValue, maxValue, s => s.Somevalue);
searcher.StringFilter(stringValue, s => s.Description);
foreach (var result in searcher._set) {
Console.WriteLine("{0} - {1}", result.Somevalue, result.Description);
}
}
static IEnumerable<SearchObject> GenerateSearchObjects() {
for (int i = 0; i < 20; i++) {
yield return new SearchObject() { Somevalue = i, Description = i % 2 == 0 ? "This one is even!" : "This one is odd!" };
}
}
}
public class Search<T> {
public IQueryable<T> _set { get; private set; }
public Search(IQueryable<T> set) { _set = set; }
public void RangeFilter(int? minValue, int? maxValue, Expression<Func<T, int>> property) {
if (minValue.HasValue) {
_set = _set.Where(s => (int)typeof(T).GetProperties().Single(p => p.Name == ((MemberExpression)property.Body).Member.Name).GetValue(s, null) >= minValue.Value);
}
if (maxValue.HasValue) {
_set = _set.Where(s => (int)typeof(T).GetProperties().Single(p => p.Name == ((MemberExpression)property.Body).Member.Name).GetValue(s, null) <= maxValue.Value);
}
}
public void StringFilter(string value, Expression<Func<T, string>> property) {
_set = _set.Where(s => ((string)typeof(T).GetProperties().Single(p => p.Name == ((MemberExpression)property.Body).Member.Name).GetValue(s, null)).Contains(value));
}
}
public class SearchObject {
public int Somevalue { get; set; }
public string Description { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment