Convert IQueryable<> type object to List<T> type?

Vikas picture Vikas · Apr 16, 2009 · Viewed 135.7k times · Source

I have IQueryable<> object.

I want to Convert it into List<> with selected columns like new { ID = s.ID, Name = s.Name }.

Edited

Marc you are absolutely right!

but I have only access to FindByAll() Method (because of my architecture).

And it gives me whole object in IQueryable<>

And I have strict requirement( for creating json object for select tag) to have only list<> type with two fields.

Answer

Marc Gravell picture Marc Gravell · Apr 16, 2009

Then just Select:

var list = source.Select(s=>new { ID = s.ID, Name = s.Name }).ToList();

(edit) Actually - the names could be inferred in this case, so you could use:

var list = source.Select(s=>new { s.ID, s.Name }).ToList();

which saves a few electrons...