views:

37

answers:

4

I have the following query which I want to sort or filter using projected class names:

List<CompanyInfo> list = new List<CompanyInfo>();

using (var db = new DbContext())
{
    list.AddRange(
                  db.Companies.Include("Projects")
                  .Select(row => new CompanyInfo()
                  {
                      ProjectCount = (from s in row.Projects
                                      where s.Company.fId == row.fId
                                      select s.pId).Count(),
                      Id = satir.fId,
                  })
                 //.OrderBy("ProjectCount") //<== what I want to do
            );
}

I want to dynamically order this query using ProjectCount or Id columns same as ESQL, like .OrderBy("ProjectCount"). Since the query result is IQueryable instead of ObjectContext it doesn't work. Is there a way to do this?

+1  A: 

You should be able to do it like this: .OrderBy(p => p.ProjectCount)

klausbyskov
+1  A: 

Take a look at the Dynamic LINQ library.
Here is a tutorial that seems to describe your case.

Devart
+1  A: 

You can do some nifty things with LINQ, if you know what to do. Maybe something like this??

        var query = db.Companies.Include("Projects").Select(row => 
            new CompanyInfo() 
            { 
                ProjectCount = (from s in row.Projects where s.Company.fId == row.fId select s.pId).Count(), 
                Id = satir.fId, 
            });

        if (orderBy) // orderBy is bool, that tels you what to order by
            query = query.OrderBy(x => x.ProjectCount);
        else
            query = query.OrderBy(x => x.Id);

        list.AddRange(query);
Euphoric
A: 

Thanks for the replies, I used helper extension methods:

Sorting in IQueryable using string as column name

Armagan