Advertisement
Guest User

Untitled

a guest
May 16th, 2013
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.34 KB | None | 0 0
  1. using MongoRepository;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Linq.Expressions;
  6.  
  7. class Program
  8. {
  9.     static void Main(string[] args)
  10.     {
  11.         MongoRepository<Foo> repo = new MongoRepository<Foo>();
  12.         var reporesult = repo.All().Where(IsInSet(new[] { 1, 4 }, 20)).ToArray();
  13.     }
  14.  
  15.     private static Expression<Func<Foo, bool>> IsInSet(IEnumerable<int> seeds, int setsize)
  16.     {
  17.         if (seeds == null)
  18.             throw new ArgumentNullException("s");
  19.  
  20.         if (!seeds.Any())
  21.             throw new ArgumentException("No sets specified");
  22.  
  23.         return seeds.Select<int, Expression<Func<Foo, bool>>>(seed => x => x.Seed % setsize == seed).JoinByOr();
  24.     }
  25. }
  26.  
  27. public class Foo : Entity
  28. {
  29.     public int Seed { get; set; }
  30. }
  31.  
  32. public static class Extensions
  33. {
  34.     public static Expression<Func<T, bool>> JoinByOr<T>(this IEnumerable<Expression<Func<T, bool>>> filters)
  35.     {
  36.         var firstFilter = filters.First();
  37.         var body = firstFilter.Body;
  38.         var param = firstFilter.Parameters.ToArray();
  39.         foreach (var nextFilter in filters.Skip(1))
  40.         {
  41.             var nextBody = Expression.Invoke(nextFilter, param);
  42.             body = Expression.Or(body, nextBody);
  43.         }
  44.         return Expression.Lambda<Func<T, bool>>(body, param);
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement