Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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; }
- }
- }
Add Comment
Please, Sign In to add comment