Search code examples
c#predicates

Is it possible to pass Take(), Skip(), OrderBy() etc. as predicates to a function?


Is this possible in an easy way or should I just add skip/take as parameters?

public IEnumerable<T> GetKittens<T>(Expression<Func<Kitten, bool>> predicate = null) where T : KittenViewModel, new()
{

  var kittenModels = GetModels(); // IQueryable<T>

  // how can I make the predicate say 'select the top 10' or 
  // 'skip 5 and take 5'

  kittenModels = kittenModels.Where(predicate); 

}

Solution

  • A predicate by definition is a Boolean test that determines if an item should be included. If there is some kind of information on the object about its position in the collection (which seems unlikely), you could use that, but your best bet is probably to just add 2 arguments (take and skip) to your method and then just do something like this:

    public IEnumerable<T> GetKittens<T>(Expression<Func<Kitten, bool>> predicate = null, int take = -1, int skip = -1) where T : KittenViewModel, new()
    {
    
      var kittenModels = GetModels(); // IQueryable<T>
    
      if(skip > 0)
        kittenModels = kittenModels.Skip(skip);
    
      if(take > 0)
        kittenModels = kittenModels.Take(take);
    
      kittenModels = kittenModels.Where(predicate); 
    
    }
    

    Note that normally, you would probably want to apply the predicate and then skip/take, but as I don't know what you are trying to do, I cannot say that for certain.