Thursday, January 5, 2012

OrderBy and GroupBy in LINQ

If you are familiar with SQL,You would know it can enable you to perform some relational operations like the data to be returned in a specific Order and get the summary values based on the rows in each group.Here the LINQ is provide the same functionality
OrderBy:
The OrderBy is used to retrieve the data in particular order.The OrderBY expects a method as its argument.This methods identifies expressions that you want to use to sort the data.
For this i will show an example to get names of each city in AllCountry array
IEnumerable citynames=Allcountry.OrderBy(acoun=>acoun.CityName).Select(City=>city.CityName)
List li=New List();
 foreach(string name in Country)
  {
         li.add(name);
  }
 foreach (string s in list) // Loop through List with foreach
  {
 Console.WriteLine(s);
  }
The OrderByDescending is get the data in descending order.Here there one method i.e ThenByDescending which is used for more than one key value
GroupBy:
The GroupBy method is used to group the data to common values in one or more Fields.The GroupBy method expects a methods that specify the fields to group the data
var citiesGroupByCountry= Allcountry.GroupBy(acoun=>acoun.Country);
foreach(var citiesPerCountry in citiesGroupByCountry)
{
 foreach(var citis in citiesPerCountry)
 {
   Console.Writeline(Country.CountyName);
 }
}

No comments:

Bel