0

I have this method, it selects data in a particular range (pageIndex and pageSize)

public PagedList(IQueryable<T> source, int pageIndex, int pageSize)
    {            
        this.AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
    }

I want to create an overloading method which selects all data, so, here's my code

public PagedList(IQueryable<T> source)
    {
       //this.AddRange(source.Select(x => new T()).ToList()); (1)
        this.AddRange(source.AsQueryable().ToList()); (2)
    }

Firstly, I tried (1), but it didn't accept T. Then I tried (2), and it's recommended that I should make parameter type INumerable instead of IQueryable. What is the solution to select all data in this case?

Thanks

Ragnarsson
  • 1,715
  • 7
  • 41
  • 74

3 Answers3

4

You can do it simply like this:

public PagedList(IEnumerable<T> source) 
{ 
    this.AddRange(source);
}
  • IEnumerable<T> as parameter type instead of IQueryable<T>, because you don't use any features specific to IQueryable<T>.
  • No AsQueryable because you simply want all data
  • No ToList as List<T>.AddRange internally already performs a copy. With ToList there would be two copy operations going on.
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • Thanks Daniel, it helps. For the record, I tried something like this.AddRange(source.Select( x => new Dokument { Beschreibung = x.Beschreibung, Dokumenttyp = x.Dokumenttyp.Bezeichnung}).ToList()); But it didn't recognize Dokument. Anyway, just keep it simple like your answer. Thanks – Ragnarsson Aug 16 '12 at 09:16
0

What would be wrong with:

public PagedList(IQueryable<T> source)
{
    this.AddRange(source.ToList());
}

Making something Queryable just to then make it a list seems weird. Especially given that source is already Queryable.

KingCronus
  • 4,509
  • 1
  • 24
  • 49
0

Both IEnumerable and IQueryable are fine, it depends only on what you actualy need.

For a better case sudy you can read this.

What is the difference between IQueryable<T> and IEnumerable<T>?

Community
  • 1
  • 1
Freeman
  • 5,691
  • 3
  • 29
  • 41