skip to Main Content

In this i have write two linq queries

  1. For Ascending order
  2. For Descending order

i have done this in one way can you guy’s suggest me to the another method for knowledge if exists.

Here is the code

// Specify the data source.
int [] scores = [79,92,98,2];

// Define the query expression for ascending order.
IEnumerable<int> scoreQuery = from score in scores orderby score ascending select score;

// Define the query expression for descending order.
var scoreQueryDesc = from score in scores orderby score descending select score;

// Execute the ascending query 
foreach (var i in scoreQuery)
{
        Console.Write(i + " ");
}

// This Console is for Next line.
Console.WriteLine();

// Execute the descending query 
foreach (var i in scoreQueryDesc)
{
        Console.Write(i + " ");
}

In the above code i have define value in two type’s

  • IEnumerable scoreQuery
  • var scoreQueryDesc

Please suggest me there is any other approach to do this

2

Answers


  1. If you want to conditionally sort ascending or descending, you could use this extension:

    public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource, TKey>(
        this IEnumerable<TSource> sequence,
        Func<TSource, TKey> keySelector,
        bool descending)
    {
        return descending
            ? sequence.OrderByDescending(keySelector)
            : sequence.OrderBy(keySelector);
    }
    

    Then your code becomes simple:

    bool descending = true; // can be set at runtime
    IEnumerable<int> scoreQuery = scores.OrderByWithDirection(i => i, descending);
    
    Login or Signup to reply.
  2. You can now write this:

    int[] scores = [79, 92, 98, 2];
    
    IEnumerable<int> scoreQuery = scores.Order();
    
    var scoreQueryDesc = scores.OrderDescending();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search