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

  • SEARCH
  • Home
  • 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 8330825
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T02:14:05+00:00 2026-06-09T02:14:05+00:00

I have a simple data class that has this signature: internal interface IMyClass {

  • 0

I have a simple data class that has this signature:

internal interface IMyClass {
    string Letter { get; }
    int Number { get; }
}

I wish to be able to sort this data based on a field (specified as string sortField) and a direction (specified as bool isAscending)

Currently I am using a switch (with the ascending logic within each case as if)

IEnumerable<IMyClass> lst = new IMyClass[];//provided as paramater
switch (sortField)
{
    case "letter":
        if( isAscending ) {
            lst = lst.OrderBy( s => s.Letter );
        } else {
            lst = lst.OrderByDescending( s => s.Letter );
        }
        break;
    case "number":
        if( isAscending ) {
            lst = lst.OrderBy( s => s.Number );
        } else {
            lst = lst.OrderByDescending( s => s.Number );
        }
        break;
}

This is pretty ugly, for 2 properties, but when the sort logic differs it becomes a problem (we also see s => s.Number is duplicated twice in the code)

Question
What is the best way to pass a boolean to choose the sort direction?

What I’ve Tried
I’ve ripped apart System.Core.dll and found the OrderBy Extension method implementations:

OrderBy:

public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
        this IEnumerable<TSource> source, 
        Func<TSource, TKey> keySelector
    ){

    return new OrderedEnumerable<TSource, TKey>(
        source, 
        keySelector, 
        null, 
        false
    );
}

OrderByDescending:

public static IOrderedEnumerable<TSource> OrderByDescending<TSource, TKey>(
        this IEnumerable<TSource> source, 
        Func<TSource, TKey> keySelector
    ){
        return new OrderedEnumerable<TSource, TKey>(
            source, 
            keySelector, 
            null, 
            true
        );
}

It appears the purpose of having 2 named methods is to abstract this boolean away. I can’t create my own extension easily as OrderedEnumberable is internal to System.Core, and writing a layer to go from bool -> methodName -> bool seems wrong to me.

  • 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-06-09T02:14:06+00:00Added an answer on June 9, 2026 at 2:14 am

    I’d say write your own extension method:

    public static IEnumerable<T> Order<T, TKey>(this IEnumerable<T> source, Func<T, TKey> selector, bool ascending)
    {
        if (ascending)
        {
            return source.OrderBy(selector);
        }
        else
        {
            return source.OrderByDescending(selector);
        }
    }
    

    Then you can just write:

    lst = lst.Order( s => s.Letter, isAscending );
    

    As for specifying method name: I hope this doesn’t come off as a cop-out answer, but I think you should stick with using a selector function instead of passing in a string. Going the string route doesn’t really save you any typing or improve clarity (is "letter" really much faster or clearer than s => s.Letter?) and only makes your code fatter (you’d either need to maintain some sort of mapping from strings to selector functions or write custom parsing logic to convert between them) and possibly more fragile (if you go the latter route, there’s a pretty high probability of bugs).

    If your intention is to take a string from user input to customize sorting, of course, you have no choice and so feel free to disregard my discouraging remarks!


    Edit: Since you are accepting user input, here’s what I mean by mapping:

    class CustomSorter
    {
        static Dictionary<string, Func<IMyClass, object>> Selectors;
    
        static CustomSorter()
        {
            Selectors = new Dictionary<string, Func<IMyClass, object>>
            {
                { "letter", new Func<IMyClass, object>(x => x.Letter) },
                { "number", new Func<IMyClass, object>(x => x.Number) }
            };
        }
    
        public void Sort(IEnumerable<IMyClass> list, string sortField, bool isAscending)
        {
            Func<IMyClass, object> selector;
            if (!Selectors.TryGetValue(sortField, out selector))
            {
                throw new ArgumentException(string.Format("'{0}' is not a valid sort field.", sortField));
            }
    
            // Using extension method defined above.
            return list.Order(selector, isAscending);
        }
    }
    

    The above is clearly not as clever as dynamically generating expressions from strings and invoking them; and that could be considered a strength or a weakness depending on your preference and the team and culture you’re a part of. In this particular case, I think I’d vote for the hand-rolled mapping as the dynamic expression route feels over-engineered.

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

Sidebar

Related Questions

In my Hibernated system, I have a class Picture that has some simple data,
I have a class State that has a string data type called moveType .
I have only simple data types in method signature of service (such as int,
I have a simple IRenderable class that has members for position, scaling, and rotation:
Say you have a simple class with some storage data structure (list, vector, queue,
I have a simple application that has a single page with a button that
I have a simple data layer routine that performs a password update, the user
I have a url that looks like this: http://localhost/store/mens/category/t-shirts/item/a-t-shirt I have a class called
I have a simple class with a property class Foo { string Title {
In Python, I have a Graph class that has a dictionary of vertex objects.

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.