C# Linq Examples
This examples shows how to use LINQ in your programs, covering the entire range of LINQ functionality.
Example 1: This example finds all elements of an array less than 7.
int[] allNumbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums1 = from n in allNumbers where n < 7 select n; //Version 1 Console.WriteLine("Numbers < 7:"); foreach (var x in lowNums1) Console.WriteLine(x); //Version 2 var lowNums2 = allNumbers.Where(n => n < 7); Console.WriteLine("Numbers < 7:"); foreach (var x in lowNums2) Console.WriteLine(x); //Both of them writes to the console window like below. // //Numbers < 7: //5 //4 //1 //3 //6 //2 //0
Example2: This example shows the partition a list of words by their first letter with "group by".
string[] words = { "banana", "apple", "strawberry", "cheese", "pineapple", "book", "angel", "section" }; var wordGroups1 = from w in words group w by w[0] into g select new { FirstLetter = g.Key, Words = g }; //Version 1 foreach (var g in wordGroups1) { Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter); foreach (var w in g.Words) Console.WriteLine(w); } var wordGroups2 = words.GroupBy(w => w[0], (key, g) => new { FirstLetter = key, Words = g }); //Version 2 foreach (var g in wordGroups2) { Console.WriteLine("Words that start with the letter '{0}':", g.FirstLetter); foreach (var w in g.Words) Console.WriteLine(w); } //Both of them writes to the console window like below. // //Words that start with the letter 'b': //banana //book //Words that start with the letter 'a': //apple //angel //Words that start with the letter 's': //strawberry //section //Words that start with the letter 'c': //cheese //Words that start with the letter 'p': //pineapple
Example3: This example uses orderby to sort a list of words by length.
string[] words = { "banana", "apple", "strawberry", "cheese", "pineapple", "book", "angel", "section" }; var sortedWords1 = from w in words orderby w.Length select w; var sortedWords2 = words.OrderBy(w => w.Length); //Version 1 Console.WriteLine("The sorted list of words by length:"); foreach (var w in sortedWords1) Console.WriteLine(w); //Version 2 Console.WriteLine("The sorted list of words by length:"); foreach (var w in sortedWords2) Console.WriteLine(w); //Both of them writes to the console window like below. // //book //apple //angel //banana //cheese //section //pineapple //strawberry