Guest User

Untitled

a guest
May 21st, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Linq.Expressions;
  5.  
  6. namespace ConsoleApplication1 {
  7. class Program {
  8. static void Main(string[] args) {
  9. int? minValue = 5;
  10. int? maxValue = 17;
  11. string stringValue = "odd";
  12.  
  13. var searcher = new Search<SearchObject>(GenerateSearchObjects().AsQueryable());
  14. searcher.RangeFilter(minValue, maxValue, s => s.Somevalue);
  15. searcher.StringFilter(stringValue, s => s.Description);
  16. foreach (var result in searcher._set) {
  17. Console.WriteLine("{0} - {1}", result.Somevalue, result.Description);
  18. }
  19. }
  20.  
  21. static IEnumerable<SearchObject> GenerateSearchObjects() {
  22. for (int i = 0; i < 20; i++) {
  23. yield return new SearchObject() { Somevalue = i, Description = i % 2 == 0 ? "This one is even!" : "This one is odd!" };
  24. }
  25. }
  26. }
  27.  
  28. public class Search<T> {
  29. public IQueryable<T> _set { get; private set; }
  30.  
  31. public Search(IQueryable<T> set) { _set = set; }
  32.  
  33. public void RangeFilter(int? minValue, int? maxValue, Expression<Func<T, int>> property) {
  34. if (minValue.HasValue) {
  35. _set = _set.Where(s => (int)typeof(T).GetProperties().Single(p => p.Name == ((MemberExpression)property.Body).Member.Name).GetValue(s, null) >= minValue.Value);
  36. }
  37. if (maxValue.HasValue) {
  38. _set = _set.Where(s => (int)typeof(T).GetProperties().Single(p => p.Name == ((MemberExpression)property.Body).Member.Name).GetValue(s, null) <= maxValue.Value);
  39. }
  40. }
  41.  
  42. public void StringFilter(string value, Expression<Func<T, string>> property) {
  43. _set = _set.Where(s => ((string)typeof(T).GetProperties().Single(p => p.Name == ((MemberExpression)property.Body).Member.Name).GetValue(s, null)).Contains(value));
  44. }
  45. }
  46.  
  47. public class SearchObject {
  48. public int Somevalue { get; set; }
  49. public string Description { get; set; }
  50. }
  51. }
Add Comment
Please, Sign In to add comment