How do I order query result in LINQ?

Category: System.Linq, viewed: 75 time(s).

In the following example you'll see how to order the result of a LINQ query. To order the result we use the orderby keyword in our query. Just like in SQL query we can order the result either in ascending order or descending order.

using System;
using System.Collections.Generic;
using System.Linq;

namespace Kodecsharp.Example.Linq
{
    class LinqOrderDemo
    {
        public static void Main(string[] args) {
            int[] numbers = { 5, 6, 2, 4, 9, 8, 1, 7, 0, 3 };

            var queryAscending = 
                from number in numbers
                orderby number ascending
                select number;

            Console.Write("Ascending Order : ");
            foreach (int number in queryAscending)
            {
                Console.Write(number + ", ");
            }
        

            var queryDescending =
                from number in numbers
                orderby number descending
                select number;

            Console.WriteLine("");

            Console.Write("Descending Order: ");
            foreach (int number in queryDescending)
            {
                Console.Write(number + ", ");
            }

            Console.ReadLine();
        }
    }
}

The program output the following result:

Ascending Order : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
Descending Order: 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Network Sites

Statistics

Locations of visitors to this page