4

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); 

}
NibblyPig
  • 51,118
  • 72
  • 200
  • 356
  • I doubt it. You could probably put a counter and state in the predicate, but that's a bit nasty and fails on re-use. Or you could use the `Kitten, int, bool` predicate signature instead which includes an index? But both will continue enumerating the source past the tenth element so aren't as nice as regular Skip/Take etc. – Rup Oct 07 '14 at 12:28
  • Thanks. Would have been nice. – NibblyPig Oct 07 '14 at 12:31

1 Answers1

6

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.

pquest
  • 3,151
  • 3
  • 27
  • 40
  • Thanks. Does it matter if the predicate line comes after skip/take? Because you'd usually want to filter first then skip/take afterwards. – NibblyPig Oct 07 '14 at 12:33
  • see my edit. Normally you would probably do the predicate first, I just inserted the skip and take where you had the comment in your method. – pquest Oct 07 '14 at 12:33