Welcome to SpellCoder Sign in | Join | Help

LINQ Project Presentation, SilverKey Demo Day 1

This is a the second part of my presentation in SKDD1
You will find the first part here
the presentation materials for part 1 & part 2 are here


So, let's have a look back to our agenda, and what we covered in the first part
In this part we will be talking about the most exciting feature in C# 3.0 which is LINQ Project.
LINQ stands for Language Integrated Queries, which means adding the concept of queries to general purpose languages in dealing with all type of data.




As a good start, let's see the problem we've been dealing with for the past decades.
Both data manipulation and logic implementation improved in different direction, while the data manipulation were treated declaratively using languages like SQL and concepts of relational algebra, on the other hand, logic implementation treated imperatively using Object oriented programming concepts and also standard control flow constructs like conditions & loops.
This small problem introduced a bigger problem which is making the application always divided into two different context
  1. The Data context
    1. Relational Databases
    2. Structured Documents (XML)
    3. Any other data store (Excel sheets, ... etc)
  2. The Logic context
and also another problem comes from dealing with different context, which is dealing with every context in a different way, so you can't easily have a join between a relational database table and an object-in-memory collection or XML document, several solutions were provided for this, but they were either too hard or too complex


So from understanding the problem, LINQ provides the solution, first it introduce a unified model of dealing with data, which all data can be treated similarly in memory, so you can have something like joining data records coming from a database table with a collection in memory then saving the results in a XML document in the same instruction.
Also LINQ is using SQL-like instructions, which are very familiar to developers, and also providing a good level of abstraction using more declarative syntax, which gives the system more space for decisions, in other words, the same instruction can be executed differently depending on the implementation of LINQ, so imagine a sorting example like this
static void Sort()
{
int[] set = new int[]{4, 1, 4, 9, 23, 5, 75, 32, 47, 0, 12};
var q = from i in set
orderby i
select i;
foreach (var i in q)
{
Console.WriteLine(i);
}
}
in the example, we displayed an unsorted integer list using the orderby clause, now imagine in the near future we could have a different implementation of the orderby clause that depends on the hardware you are running on, so for a multi-core environment the internal implmenetation could be different than single core



LINQ Architecture is very elegant and simple, as shown in the slide it provides queries for both C# 3 & VB9 as a first class citizen, and also it provides an abstraction for different implementations of LINQ like LINQ-To-Objects, LINQ-To-SQL (DLINQ) and LINQ-To-XML (XLINQ).
In addition it provides a good extensibility model to implement LINQ on different data stores.
so first starting with

LINQ To Objects
We will see two different examples on using LINQ syntax on arrays, the first example is joining two different arrays of integers and finding the matching set.

static void LinqJoin()
{
int[] set1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] set2 = {5, 6, 7, 8, 9, 10, 11, 12, 13, 14};

var query = from i in set1
join j in set2 on i equals j into matches
select matches;

foreach(var q in query)
foreach(var i in q)
Console.WriteLine(i);
}
and this will result the following
5
6
7
8
9
10
which is common elements between the two sets.

The second example will be a grouping example, using a string array we will write a snippet of code which is going to group the strings in the array by the length of every string, so the words with the same length comes together
static void LinqGroupBy()
{
string[] names = {"Mohammed", "Ahmed", "Mostafa", "Tamer", "Dody", "Taher", "Adam", "Kent", "Rafik"};
var groups = from name in names
orderby name.Length
group name by name.Length into g
select g;


//var groups = names. // OrderBy(i=>i.Length). // GroupBy(i=>i.Length); foreach(var group in groups)
{
Console.WriteLine(group.Key);
foreach(var name in group)
Console.WriteLine(name);
}

}
and this will result the following
4
Dody
Adam
Kent
5
Ahmed
Rafik
Taher
Tamer
7
Mostafa
8
Mohammed
so you can see, the result is an array of groups, every group contains a key and a collection of elements included in the group.
I think you noticed some documented code lines, these lines are equivalent to the linq query, but using the Lambda Expressions.

LINQ To SQL (DLINQ)
Now we come to the second part which is DLINQ.
DLINQ is providing a new model for dealing with relational databases, so no more SqlConnection & SqlCommand ... etc, most of the time you'll never need them again, because under the hoods Dlinq is doing this job for you, everything is hidden under the System.Data.DLinq.DataContext class, all what you have to do, is inheriting from this class and define the different tables and relations in your database using the new attributes TableAttribute and ColumnAttribute.
However, Dlinq comes with a command line tool called SqlMetal, which is doing this job for you, all what you need to do is to call the SqlMetal with the proper parameters
as sample of using SqlMetal

> SqlMetal.exe /server:(local) /database:Northwind /pluralize /sprocs /code:Northwind.cs

In this example I'm telling the SqlMetal, to use the Northwind database on local server, and to include the stored procedures and also output the generated code in the Northwind.cs file.

However, if you are using VS 2005 professional, you can use a graphical interface for this, and SqlMetal will be executed with every compilation.
To do so, after creating your LINQ project file, right click on the project in the Solution Explorer and click Add->New Item

Then select DLinqObjects file and click Add

An empty area will be displayed, open the Server Explorer and connect to a database, for example Northwind Database, and then navigate through the tree to tables, then drage the Customers and Orders Tables
you'll end up with a similar screen


So, now you will notice that the relation between the two tables is displayed as well as all the columns in both tables.
now try to build the project, then navigate the dlinqobject1.cs file under the dlinqobject1.dlinq in the Solution Explorer, you will see the generated code, remember you have to build the project to see the code.
Now you are ready to write some code to play with Dlinq
static void DLinqSample1()
{
NorthwindDataContext db = new NorthwindDataContext();
var q = from c in db.Customers
where c.City == "London" select c;
foreach(var c in q)
Console.WriteLine(c.CustomerID);
}
So first, make a new object of your database, which is here NorthwindDataContext, then write the query you want, in this example we are reading all the customers located in London, and then displaying the CustomerID's

LINQ To XML (XLINQ)
Now let's do something cool, what about querying the data from the Customer table then converting the result into Xml document.
LINQ project provides set of new classes all starts with X, like XElement, XAttribute, XDocument, ... etc
These classes are ready to accept queries as parameters to its constructor, and process the query and add the results as child nodes to the current constructed node
so lets see an example
internal static void DLinqSample2()
{
NorthwindDataContext db = new NorthwindDataContext();
var root = new XElement("Customers",
from c in db.Customers
where c.City == "London" select new XElement("Customer",
new XElement("CustomerID", c.CustomerID),
new XElement("CompanyName", c.CompanyName)));


Console.WriteLine(root);

}
so the result of this query will be
<Customers>
<Customer>
<CustomerID>AROUT</CustomerID>
<CompanyName>Around the Horn</CompanyName>
</Customer>
<Customer>
<CustomerID>BSBEV</CustomerID>
<CompanyName>B's Beverages</CompanyName>
</Customer>
.............
</Customers>
In the example we can see how we passed the query itself as a parameter to the XElement constructor.
and also we changed the output of the query itself in the select clause to create XEelements instead of just returning the results.


These are some related topics that you may feel interested to check.


These are some references & resources


Here you can find my contacts for more questions and information.

I hope I could cover both C# 3.0 Language Enhancements & LINQ Project in a good way, I hope if you have any question just leave me a comment and I'll answer you as soon as possible.

Thanks and see you in SilverKey Demo Day 2

kick it on DotNetKicks.com
Published Tuesday, January 02, 2007 7:54 PM by Mohammed Hossam
Filed Under: , ,

Comments

# LINQ Project Presentation, SilverKey Demo Day 1

Thursday, January 04, 2007 5:53 PM by ALT-TAB Forums
Linked for good information - Forum Post.
Anonymous comments are disabled