Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 242633
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T20:51:14+00:00 2026-05-11T20:51:14+00:00

For my generic grid I currently do this to activate the sorting: Elements.OrderBy(column.SortExpression).AsQueryable(); In

  • 0

For my generic grid I currently do this to activate the sorting:

Elements.OrderBy(column.SortExpression).AsQueryable();

In which SortExpression is of type Func<T, object> and column is a generic class Column<T>

I set SortExpression in a controller like this:

new Column<OrderViewData>{Key = "ShippingDate", SortExpression = e => e.ShippingDate}

The ‘OrderBy’ causes an execution of the sql statement, which I don’t want.

So I’m trying to replace it with this:

Elements = from element in Elements
               orderby column.SortExpression
               select element;

Which doesn’t trigger the sql execution.

Now, of course column SortExpression should be of another type. Only I can’t really figure out what type it should be and how to set it on the generic class in the controller.

I should still be able to set SortExpression in a generic strong typed way of some sort.

Any suggestions on how I can order by an expression set somewhere else in the application, without executing the sql when applying the order to the IQueryable?

@ Earwicker:

This works:

Expression<Func<Employee, DateTime?>> sortexpression = e => e.BirthDate;

var db = new NorthwindDataContext();
var query = from e in db.Employees
                select e;
query = query.OrderBy(sortexpression);

int count = query.Count();

And generates:

SELECT COUNT(*) AS [value]
FROM [dbo].[Employees] AS [t0]

When I replace DateTime? in the first line with object:

Expression<Func<Employee, object>> sortexpression = e => e.BirthDate;

I get this exception :

InvalidOperationException: Cannot order by type ‘System.Object’

Now, you might say: "then just use DateTime?", but I’d like building the columns in my generic grid to require the least amount of code possible. I don’t want people to have to type the whole Expression<Func<Employee, some_type>>. I want people to be able to just type something small like my first attempt SortExpression = e => e.BirthDate, where I take advantage of the generic Column class to define ‘T’.

Do you think it would be possible to create some kind of extension that somehow gets the type of e.BirthDate and then casts the Func<T, object> to Expression<Func<T,some_type>> ?
Then I could do something in the internal code like:
Elements.OrderBy(column.SortExpression.FixCast())

I don’t care much that my internal code is ugly or complex at this moment. I need to get the SQL queries right & take care of usability for developers using the grid.

Thanks a lot for helping me out!

@ earwicker 2:

var gridBuilder = new RainbowGridBuilder<Employee> ("Examples_Employees") 
{
    
    Elements = GetEmployees(),
    //The elements (records) we will show in our grid. 
    
    //Define the columns for our grid.
    Columns = new List<Column<Employee >> 
    {
        new Column<Employee> 
        {
            Key = "EmployeeId", 
            //Key is used for sorting, selecting columns, ...
            
            Header = "Employee Id", 
            //The header of the column. Also used as caption in the column selection checkboxlist.
            
            ValueExpression = e => e.EmployeeID.ToString(), 
            
            //The Linq expression which will be executed on each element to fill the cell
            
            SortExpression = e => e.EmployeeID, 
            //The Linq expression by which to sort the elements in the grid. 
            
            Display = false
        }, //Is this column visible by default?
      
        new Column<Employee> 
        {
            Key = "Name",
            ValueExpression = e => 
                e.FirstName + " " + e.LastName,
            SortExpression = e => e.LastName
      } ,
    },

    // Some other properties here that are irrelevant.
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-11T20:51:14+00:00Added an answer on May 11, 2026 at 8:51 pm

    I came up with a solution that achieves what I was after.

    Usage: Setting strong typed sortexpression on columns:

    Columns = new List<Column<Employee>>{
                new Column<Employee> {
                    Key = "EmployeeId",   
                    SortExpression = new SortExpression<Employee>(e => e.EmployeeID)
                    // ... other irrelevant column properties ...  
                },
                new Column<Employee> {
                    Key = "EmployeeBirthDate",      
                    SortExpression = new SortExpression<Employee>(e => e.BirthDate)
                }
              };
    

    Underlying code

    These few lines in the “buildGrid()” method in class RainbowGridBuilder apply the sorting:

    if (columnToSort != null) //sort the elements according to the set column key and the sortexpression
    {
        var column = Columns.Where(c => c.Key == columnToSort).SingleOrDefault();
        if (column != null)
        {
            Elements = column.SortExpression.ApplySortExpression(Elements, descending);
        }
    }
    

    How it works:

    Trough the use of overloaded constructors in the SortExpression class that I made I can set a private Expression<Func<T, some_specific_Type>>.

    Inside the SortExpression class is a method ApplySortExpression that searches for a non-null private member and sorts accordingly:

    public class SortExpression<T>
    {
        private Expression<Func<T, DateTime?>> DateTimeExpression { get; set; }
        private Expression<Func<T, int?>> intExpression { get; set; }
        private Expression<Func<T, string>> stringExpression { get; set; }
    
        public SortExpression(Expression<Func<T, DateTime?>> expression)
        {
            DateTimeExpression = expression;
        }
    
        public SortExpression(Expression<Func<T, int?>> expression)
        {
            intExpression = expression;
        }
    
        public SortExpression(Expression<Func<T, string>> expression)
        {
            stringExpression = expression;
        }
    
        public IQueryable<T> ApplySortExpression(IQueryable<T> elements, bool? descending)
        {
            if (DateTimeExpression != null)
            {
                if (descending.HasValue && descending.Value)
                    return elements.OrderByDescending(DateTimeExpression);
                else
                    return elements.OrderBy(DateTimeExpression);
            }
            else if (intExpression != null)
            {
                if (descending.HasValue && descending.Value)
                    return elements.OrderByDescending(intExpression);
                else
                    return elements.OrderBy(intExpression);
            }
            else if (stringExpression != null)
            {
                if (descending.HasValue && descending.Value)
                    return elements.OrderByDescending(stringExpression);
                else
                    return elements.OrderBy(stringExpression);
            }
            else
                throw new Exception("Unsuported sortkey type");
        }
    }
    

    This solution may not be super clean under the hood, but it’s the usability that I was after. The only change to the consuming code was to add “new SortExpression<Employee>“.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 223k
  • Answers 223k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Kind of hard to say, but I think what you're… May 13, 2026 at 12:34 am
  • Editorial Team
    Editorial Team added an answer Take a look at micro_proxy. It implements all the basic… May 13, 2026 at 12:34 am
  • Editorial Team
    Editorial Team added an answer LINQ is a base technology - as others have already… May 13, 2026 at 12:34 am

Related Questions

I've got a MenuItem whos ItemsSource is databound to a simple list of strings,
Ok - I'm pulling my hair out over what I thought was a simple
I'm just mucking about with custom controls in silverlight and for the life of
I'm trying to build a generic grid view in an ASP.NET MVC application. Let

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.