Skip to main content

A few LINQ examples.

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

string[] names = { "Tom", "Dick", "Harry" };

//-------------------------
// standard query operators
//-------------------------
IEnumerable<string> filteredNames = System.Linq.Enumerable.Where(names, n => n.Length >= 4);
  foreach (string n in filteredNames) {
    Console.WriteLine (n); // Dick, Harry
  }

//standard query operators
IEnumerable<string> filteredNames = names.Where (n => n.Contains ("a"));
  foreach (string name in filteredNames) {
    Console.WriteLine (name); // Harry
  }

//-------------------------
// Chaining Query Operators example
//-------------------------
IEnumerable<string> query = names
  .Where (n => n.Contains ("a"))
  .OrderBy (n => n.Length)
  .Select (n => n.ToUpper());
  
  foreach (string name in query) {
    Console.WriteLine (name); // JAY, MARY, HARRY
  }

//-------------------------
// Subqueries
//-------------------------
// A subquery is a query contained within another query's lambda expression. The
// following example uses a subquery to sort musicians by their last name:
string[] musicians = { "David Gilmour", "Roger Waters", "Rick Wright", "Nick Mason" };
IEnumerable<string> query = musicians.OrderBy (m => m.Split().Last());

  foreach (string musician in query) {
    Console.WriteLine (musician);
  }

//-------------------------
// Enumerable.Where implementation
//-------------------------
string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
IEnumerable<string> query = names.Where (name => name.EndsWith ("y"));
// Result: { "Harry", "Mary", "Jay" }

// A where clause can appear more than once in a 
// query and be interspersed with let, orderby and join clauses:
from n in names
  where n.Length > 3
  let u = n.ToUpper()
  where u.EndsWith ("Y")
  select u; // Result: { "HARRY", "MARY" }
  

//-------------------------
// Select subqueries and object hierarchies
//-------------------------
// You can nest a subquery in a select clause to build an object hierarchy. The following
// example returns a collection describing each directory under D:\source, with
// a subcollection of files under each directory:
DirectoryInfo[] dirs = new DirectoryInfo(@"d:\source").GetDirectories();

var query =
   from d in dirs
   where (d.Attributes & FileAttributes.System) == 0
   select new {
                DirectoryName = d.FullName,
                Created = d.CreationTime,
                Files = from f in d.GetFiles()
                  where (f.Attributes & FileAttributes.Hidden) == 0
                  select new {FileName = f.Name, f.Length,}
              };

foreach (var dirFiles in query) {
   Console.WriteLine("Directory: " + dirFiles.DirectoryName);
   
   foreach (var file in dirFiles.Files) {
       Console.WriteLine(" " + file.FileName + " Len: " + file.Length);
   }
}