Sorting and Grouping


The evaluation of a query expression results in a sequence of values that are produced in some order that is intrinsic in the underlying information sources. To give developers explicit control over the order in which these values are produced, standard query operators are defined for controlling the order. The most basic of these operators is the OrderBy operator.

The OrderBy and OrderByDescending operators can be applied to any information source and allow the user to provide a key extraction function that produces the value that is used to sort the results. OrderBy and OrderByDescending also accept an optional comparison function that can be used to impose a partial order over the keys.


Example:









using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;




    namespace ConsoleApplication1

     {

     class Program

{

     [STAThread]

     static void Main(string[] args)

{




     string[] names = { "Ajay", "Rajesh", "Shubhankar",

     "Ravi", "Preeti", "Tulika",

    "Anup", "Saurabh" };


    

IEnumerable<string> expr = from s in names

     where s.Length < 8

     orderby s

     select s.ToUpper();


    

foreach (string item in expr)

     Console.WriteLine(item);

     string[] names1 = { "Ajay", "Rajesh", "Shubhankar",

"Ravi", "Preeti", "Tulika",

"Anup", "Saurabh" };


    

// group by length

     var groups = names1.GroupBy(s => s.Length);


    

foreach (IGrouping<int, string> group in groups)

     {

     Console.WriteLine("Strings of length {0}", group.Key);


    

foreach (string value in group)

     Console.WriteLine(" {0}", value);

     }


    

      Console.ReadKey();

     }

    }

  }



Output



                    

Aspnet Related Tutorials

...more

New Aspnet Resources

...more

Copyright © 2013 VisualBuilder. All rights reserved