Monday, June 1, 2015

Hello LINQ

Hello LINQ

Method 1

In the method below, StackTrack class is used here to display the name of the method being used by the class at runtime.

static void YourCode()
  {

    Console.WriteLine("{0} : Begin", new  StackTrace(0, 


       true).GetFrame(0).GetMethod().Name);

    // Do whatever you want in here.

   Console.WriteLine("{0} : End", new StackTrace(0,true).GetFrame(0).GetMethod().Name);

  }

Method 2

The method below is using String.EndsWith method to extract a string from an array.

static void Listing1_1()

  {

    Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

    string[] greetings = { "hello world", "hello LINQ", "hello Apress" };

   var items =

     from s in greetings

     where s.EndsWith("LINQ")

     select s;


    foreach (var item in items)

    Console.WriteLine(item);

    Console.WriteLine("{0} : End", new StackTrace(0,  true).GetFrame(0).GetMethod().Name);

  }

Method 3

XElement loads and parses XML. The method below shows the use of XElement from LINQ. We use it to load an XML document. We then query it using expressions in the C# language.

static= void Listing1_2()

{

Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);



System.Xml.Linq.XElement books = System.Xml.Linq.XElement.Parse(

@"<books>

<book>

<title>Pro LINQ: Language Integrated Query in C# 2010</title>

<author>Joe Rattz</author>

</book>

<book>

<title>Pro .NET 4.0 Parallel Programming in C#</title>

<author>Adam Freeman</author>

</book>

<book>

<title>Pro VB 2010 and the .NET 4.0 Platform</title>

<author>Andrew Troelsen</author>

</book>

</books>");



var titles =

from book in books.Elements("book")

where (string)book.Element("author") == "Joe Rattz"

select book.Element("title");

foreach (var title in titles)

Console.WriteLine(title.Value);



Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

}

Method 4

Before executing the below method, an object model of the database is created with Nant. The method is used to retrieve result from the database table 'Customers' using LINQ

static void Listing1_3()

{

Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

Northwind db = new Northwind(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;");

var custs =

from c in db.Customers

where c.City == "Rio de Janeiro"

select c;



foreach (var cust in custs)

Console.WriteLine("{0}", cust.CompanyName);



Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

}

Method 5

The method below converts string array into int array using LINQ.

static void Listing1_4()

{

Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

string[] numbers = { "0042", "010", "9", "27" };

int[] nums = numbers.Select(s => Int32.Parse(s)).ToArray();

foreach (int num in nums)

Console.WriteLine(num);

Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

}

Method 6

The method below converts string array into int array and displays the result in ascending order of numbers using LINQ.

static void Listing1_5()

{

Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

string[] numbers = { "0042", "010", "9", "27" };

int[] nums = numbers.Select(s => Int32.Parse(s)).OrderBy(s => s).ToArray();

foreach (int num in nums)

Console.WriteLine(num);

Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

}

Method 7

The example below uses method GetEmployees() of Employee class of LINQDev.HR namespace to get the details of the employees. Using LINQ pattern the employees details are cast to Contact class of LINQDev.Common namespace. Then the employee details are printed using PublishContacts() method of LINQDev.Common namespace.

static void Listing1_6()

{

Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

ArrayList alEmployees = LINQDev.HR.Employee.GetEmployees();

LINQDev.Common.Contact[] contacts = alEmployees

.Cast()

.Select(e => new LINQDev.Common.Contact {

Id = e.id,

Name = string.Format("{0} {1}", e.firstName, e.lastName)

})

.ToArray();



LINQDev.Common.Contact.PublishContacts(contacts);



Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

}



// The following namespaces are used for Listing1_6.

namespace LINQDev.HR

{

public class Employee

{

public int id;

public string firstName;

public string lastName;



public static ArrayList GetEmployees()

{

// Of course the real code would probably be making a database query

// right about here.

ArrayList al = new ArrayList();



al.Add(new Employee { id = 1, firstName = "Joe", lastName = "Rattz" });

al.Add(new Employee { id = 2, firstName = "William", lastName = "Gates" });

al.Add(new Employee { id = 3, firstName = "Anders", lastName = "Hejlsberg" });

return (al);

}

}

}



namespace LINQDev.Common

{

public class Contact

{

public int Id;

public string Name;



public static void PublishContacts(Contact[] contacts)

{

// This publish method just writes them to the console window.

foreach (Contact c in contacts)

Console.WriteLine("Contact Id: {0} Contact: {1}", c.Id, c.Name);

}

}

}

Method 8

The example filters the records of the Customer table in Northwind database. It displays the details of the customers who are located in Country "USA" and Region "WA"

static void Listing1_7()

{

Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);



Northwind db = new Northwind(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind");



var orders = db.Customers

.Where(c => c.Country == "USA" && c.Region == "WA")

.SelectMany(c => c.Orders);



foreach(var order in orders)

{

Console.WriteLine(order.CustomerID + " " + order.Customer.Address + " " + order.Customer.Country);

}

Console.WriteLine(orders.GetType());



Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

}

Method 9

static void Listing1_8()

{

Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);



Northwind db = new Northwind(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;");



IEnumerable orders = db.Customers

.Where(c => c.Country == "USA" && c.Region == "WA")

.SelectMany(c => c.Orders);



foreach (Order item in orders)

Console.WriteLine("{0} - {1} - {2}", item.OrderDate, item.OrderID, item.ShipName);



Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

}

Method 10

The example below displays only those string from the ArrayList whose length is less then 7.

static void Listing1_9()

{

Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);



// legacy collection used

ArrayList arrayList = new ArrayList();

// Sure wish I could use collection initialization here, but that

// doesn't work with legacy collections.

arrayList.Add("Adams");

arrayList.Add("Arthur");

arrayList.Add("Buchanan");



IEnumerable names = arrayList.Cast().Where(n => n.Length < 7);

foreach (string name in names)

Console.WriteLine(name);



Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

}

Method 11

static void Listing1_10()

{

Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);



string[] strings = { "one", "two", null, "three" };



Console.WriteLine("Before Where() is called.");

IEnumerable ieStrings = strings.Where(s => s.Length == 3);

Console.WriteLine("After Where() is called.");



foreach (string s in ieStrings)

{

Console.WriteLine("Processing " + s);

}



Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

}

Method 12

IQueryable is an Interface which provides functionality to evaluate queries against a specific data source wherein the type of the data is not specified.

static void Listing1_11()

{

Console.WriteLine("{0} : Begin", new StackTrace(0, true).GetFrame(0).GetMethod().Name);



Northwind db = new Northwind(@"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;");



db.Log = Console.Out;



System.Linq.IQueryable orders = from c in db.Customers

from o in c.Orders

where c.Country == "USA" && c.Region == "WA"

select o;



foreach (Order item in orders)

Console.WriteLine("{0} - {1} - {2}", item.OrderDate, item.OrderID, item.ShipName);



Console.WriteLine("{0} : End", new StackTrace(0, true).GetFrame(0).GetMethod().Name);

}

No comments:

Post a Comment