<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Marius Bancila's Blog &#187; LINQ</title>
	<atom:link href="http://mariusbancila.ro/blog/category/it/software/net/linq/feed/" rel="self" type="application/rss+xml" />
	<link>http://mariusbancila.ro/blog</link>
	<description>Sharing my opinions and ideas!</description>
	<lastBuildDate>Fri, 06 Apr 2012 13:45:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>My CodeGuru Articles on LINQ</title>
		<link>http://mariusbancila.ro/blog/2007/06/06/my-codeguru-articles-on-linq/</link>
		<comments>http://mariusbancila.ro/blog/2007/06/06/my-codeguru-articles-on-linq/#comments</comments>
		<pubDate>Wed, 06 Jun 2007 07:25:16 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=46</guid>
		<description><![CDATA[Recently CodeGuru published the last part of my introductory series of articles on LINQ. Here are the links to the articles: Introduction to LINQ, part 1: LINQ to objects Introduction to LINQ, part 2: LINQ to XML Introduction to LINQ, part 3: LINQ to SQL I hope you&#8217;ll enjoy and benefit from the reading.]]></description>
			<content:encoded><![CDATA[<p>Recently CodeGuru published the last part of my introductory series of articles on LINQ. Here are the links to the articles:</p>
<ul>
<li><a target="_blank" href="http://www.codeguru.com/csharp/csharp/net30/article.php/c13699/">Introduction to LINQ, part 1: LINQ to objects</a></li>
<li><a target="_blank" href="http://www.codeguru.com/csharp/csharp/net30/article.php/c13715/">Introduction to LINQ, part 2: LINQ to XML</a></li>
<li><a target="_blank" href="http://www.codeguru.com/csharp/csharp/net30/article.php/c13799/">Introduction to LINQ, part 3: LINQ to SQL</a></li>
</ul>
<p>I hope you&#8217;ll enjoy and benefit from the reading.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2007/06/06/my-codeguru-articles-on-linq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Performance of LINQ Queries</title>
		<link>http://mariusbancila.ro/blog/2007/05/10/performance-of-linq-queries/</link>
		<comments>http://mariusbancila.ro/blog/2007/05/10/performance-of-linq-queries/#comments</comments>
		<pubDate>Thu, 10 May 2007 14:48:45 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=40</guid>
		<description><![CDATA[When I delivered the LINQ presentation at the RONUA meeting in April, I was asked how does LINQ perform on big data sets. To answer that I decided to test LINQ to XML against a 100+MB file. I decided to extract three different sets of data from this XML file: 1 set representing about 0.5MB [...]]]></description>
			<content:encoded><![CDATA[<p>When I delivered the LINQ presentation at the RONUA meeting in April, I was asked how does LINQ perform on big data sets. To answer that I decided to test LINQ to XML against a 100+MB file. I decided to extract three different sets of data from this XML file:</p>
<ul>
<li>1 set representing about 0.5MB of the XML file,</li>
<li>1 set representing about 10MB of the XML file, and</li>
<li>1 set representing about 80MB of the XML file</li>
</ul>
<p>Of course, I designed some data structures to map on the data from the XML file and run three queries against this file that would project instances of those data structures. The result was that all the three (different) queries took about same time to execute and generate my internal objects. Each time the entire file was re-parsed. The time for each query was about 3.5 seconds. Thus, I can draw two conclusions:</p>
<ul>
<li>LINQ is very performant: it took less than 12 seconds to extract 90% of the data from a 100MB file; the performance is several times greater than the one I get in C++ for parsing the file; not to mention that the code is more than several times simpler;</li>
<li>there was&#8217;t too much difference between extracting 0.5MB or 100 times that;</li>
</ul>
<p>I am quite confident that LINQ to SQL is as performant as LINQ to XML. If I&#8217;ll find a really big data base, I will query it.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2007/05/10/performance-of-linq-queries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ to SQL</title>
		<link>http://mariusbancila.ro/blog/2007/04/25/linq-to-sql/</link>
		<comments>http://mariusbancila.ro/blog/2007/04/25/linq-to-sql/#comments</comments>
		<pubDate>Wed, 25 Apr 2007 12:12:43 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=37</guid>
		<description><![CDATA[LINQ to SQL is an API that allows querying relational databases. The samples in this post are based on the concepts of: Entity classes (which are instances of Entity Types). Such a class is a regular .NET class that is decorated with the attribute Table and its properties and fields with the attribute Column DataContext, [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ to SQL is an API that allows querying relational databases. The samples in this post are based on the concepts of:</p>
<ul>
<li>Entity classes (which are instances of Entity Types). Such a class is a regular .NET class that is decorated with the attribute Table and its properties and fields with the attribute Column</li>
<li>DataContext, is the channel for doing operations with the database; it is used like an ADO.NET connection; actually its constructor takes either a connection string or an ADO.NET connection</li>
</ul>
<p>Considering the known Winner class from the previous posts, </p>
<pre class="prettyprint">
public class Winner
{
     public string Name { get; set; }
     public string Country { get; set; }
     public int Year { get; set; }
}
</pre>
<p><br/></p>
<p>Decorating it with Table and column like this</p>
<pre class="prettyprint">
[Table(Name = "Winners")]
public class Winner
{
    [Column]
    public string Name { get; set; }

    [Column]
    public string Country { get; set; }

    [Column(IsPrimaryKey = true)]
    public int Year { get; set; }
}
</pre>
<p><br/></p>
<p>will create a direct mapping between Winner and the table call Winners, and between the fields Name, Country and Year of the class and the columns with the same name from the table. Both Table and Column have several properties. One of them is Name, which specifies the actual name of the table or column corresponding to the class or property. If the property Name is not specified, the same name as for the class and properties is used.</p>
<p>Assuming we have a SQL Server database, located at C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\UCL.mdf, with a table Winners that has three columns Year (which is also the primary key), Name and Country, and that this table is populated with the winners of UEFA Champions League, we could write the following code to retrieve and show the winners:</p>
<pre class="prettyprint">
public void PrintWinners()
{
     // creates a data context that takes the path of the database
     DataContext dc = new DataContext(@"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\UCL.mdf");

     // retrieves a Table of Winner
     Table<Winner> winners = dc.GetTable<Winner>();

     // creates a sequence of winners ordered descending by the winning year
     var result = from w in winners
                  orderby w.Year descending
                  select w;

     // prints the sequence of winners
     foreach (var w in result)
     {
          Console.WriteLine("{0} {1}, {2}",
          w.Year, w.Name, w.Country);
     }
}
</pre>
<p><br/></p>
<p>First, we must instantiate a DataContext, passing as argument the path to the database. DataContext has a method GetTable, that returns a Table<T>. To get the winners we call it as shown above. On this table, we can perform a query and show the results:</p>
<pre class="prettyprint">
2006 Barcelona, Spain
2005 Liverpool, England
2004 FC Porto, Portugal
2003 AC Milan, Italy
2002 Real Madrid, Spain
2001 Bayern Munchen, Germany
2000 Real Madrid, Spain
1999 Manchester Utd., England
1998 Real Madrid, Spain
1997 Borussia Dortmund, Germany
1996 Juventus, Italy
1995 AFC Ajax, Netherlands
1994 AC Milan, Italy
1993 Olympique de Marseille, France
</pre>
<p><br/></p>
<p>It is however recommended that we use a so called strongly-typed version of DataContext. In other words, a derived class from DataContext that keeps as members all the table collections. In this case we don&#8217;t have to call directly GetTable&lt;&gt;();</p>
<pre class="prettyprint">
public class UCLDataContext : DataContext
{
    public Table<Winner> Winners;

    public UCLDataContext(string connection)
      :
      base(connection)
    {}
}
</pre>
<p><br/></p>
<p>The PrintWinnes function would have to change to:</p>
<pre class="prettyprint">
public void PrintWinners()
{
    // creates a data context that takes the path of the database
    UCLDataContext dc = new UCLDataContext(@"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\UCL.mdf");

    // creates a sequence of winners ordered descending by the winning year
    var result = from w in dc.Winners
                 orderby w.Year descending
                 select w;

    // prints the sequence of winners
    foreach (var w in result)
    {
        Console.WriteLine("{0} {1}, {2}",
            w.Year, w.Name, w.Country);
    }
}
</pre>
<p><br/></p>
<p>Only querying the database is not enough. DataContext also allow us to submit changes to the database.</p>
<p>The following function shows how to add a winner to the table Winners:</p>
<pre class="prettyprint">
public void AddWinner()
{
     // creates a data context that takes the path of the database
     UCLDataContext dc = new UCLDataContext(@"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\UCL.mdf");

     // adds a new winner to the table
     dc.Winners.Add(new Winner { Name = "Manchester United", Country = "England", Year = 2007});

     // submites the changes
     dc.SubmitChanges();
}
</pre>
<p><br/></p>
<p>If you want for instance to remove all the winners from Spain, we can do the following:</p>
<pre class="prettyprint">
public void DeleteWinner()
{
    // creates a data context that takes the path of the database
    UCLDataContext dc = new UCLDataContext(@"C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\UCL.mdf");

    // remove a sequence of winners
    dc.Winners.RemoveAll(from w in dc.Winners
                      where w.Country == "Spain"
                      select w);

    // submites the changes
    dc.SubmitChanges();
}
</pre>
<p><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2007/04/25/linq-to-sql/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>LINQ Presentation and Demos Available for Download</title>
		<link>http://mariusbancila.ro/blog/2007/04/22/linq-presentation-and-demos-available-for-download/</link>
		<comments>http://mariusbancila.ro/blog/2007/04/22/linq-presentation-and-demos-available-for-download/#comments</comments>
		<pubDate>Sun, 22 Apr 2007 09:28:57 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Events]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=35</guid>
		<description><![CDATA[On Saturday, April 22, I delivered a presentation on LINQ at a meeting of the RONUA community in Timisoara. The presentation was focused on sample codes for LINQ to Objects, LINQ to XML and LINQ to SQL. Today I uploaded on the site the presentation and demo programs so that you can download them. Here [...]]]></description>
			<content:encoded><![CDATA[<p>On Saturday, April 22, I delivered a presentation on LINQ at a meeting of the <a title="Romania .NET User Association web page" href="http://www.ronua.ro" target="_blank">RONUA</a> community in Timisoara. The presentation was focused on sample codes for LINQ to Objects, LINQ to XML and LINQ to SQL. Today I uploaded on the site the presentation and demo programs so that you can download them.</p>
<p>Here is the list of downloads:</p>
<ul>
<li>power point <a title="LINQ PowerPoint Presentation" href="http://www.mariusbancila.ro/archives/linq/IntroducereinLINQ.zip">presentation in Romanian</a> (88.5 KB); requires PowerPoint 2007</li>
<li><a title="LINQ demo programs" href="http://www.mariusbancila.ro/archives/linq/LinqDemos.zip">demo programs</a>: a solution with three VC# projects (16.2 KB): LinqToObjects, LinqToXML and LinqToSQL; requires Visual Studio Orcas March CTP; comments are in English</li>
<li><a title="SQL Server 2005 Express Edition database" href="http://www.mariusbancila.ro/archives/linq/UCL.zip">UCL database</a> (135 KB): SQL Server 2005 Express database required by the LinqToSQL project</li>
</ul>
<p>Make sure that in the LinqToSQL project you use the right path for the UCL.mdf file. Please post any kind of comments you might have about it.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2007/04/22/linq-presentation-and-demos-available-for-download/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ to XML</title>
		<link>http://mariusbancila.ro/blog/2007/04/17/linq-to-xml/</link>
		<comments>http://mariusbancila.ro/blog/2007/04/17/linq-to-xml/#comments</comments>
		<pubDate>Tue, 17 Apr 2007 16:21:27 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=32</guid>
		<description><![CDATA[LINQ offers an API called LINQ to XML, formally known as XLinq, that provides support for working with XML. This API resides in the System.Xml.Linq namespace, and you need to add a reference to the assembly with the same name to be able to use it. If you installed the Orcas March CTP bits, the [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ offers an API called LINQ to XML, formally known as XLinq, that provides support for working with XML. This API resides in the System.Xml.Linq namespace, and you need to add a reference to the assembly with the same name to be able to use it. If you installed the Orcas March CTP bits, the assembly can be found in folder C:\Windows\Microsoft.NET\Framework\v3.5.20209.</p>
<p>In the namespace you can find classes such as XNode, XElement, XAttribute, XText, etc.</p>
<p>XElement implements an XML element. It has several constructor.  The following snippet constructs an empty element called winner.</p>
<pre class="prettyprint">
   XElement root = new XElement("winner");
   Console.WriteLine(root.ToString());
</pre>
<p><br/></p>
<p>The output is </p>
<pre class="prettyprint">
< winner />
</pre>
<p><br/></p>
<p>Overloaded constructor can take additional parameters. If we pass a string:</p>
<pre class="prettyprint">
XElement root = new XElement("winner", "Manchester Utd.");
</pre>
<p><br/></p>
<p>We get:</p>
<pre class="prettyprint">
< winner >Manchester Utd.< /winner >
</pre>
<p><br/></p>
<p>We can also pass an Xattribute</p>
<pre class="prettyprint">
XElement root = new XElement("winner", "Manchester Utd.",
                             new XAttribute("Year", 1999));
</pre>
<p><br/></p>
<p>Or</p>
<pre class="prettyprint">
XElement root = new XElement("winner", new XAttribute("Year", 1999),
                             "Manchester Utd.");
</pre>
<p></br></p>
<p>In this case the winner element will have an attribute called <i>Year</i> having the value <i>1999</i>, and the text of the element will be <i>Manchester Utd.</i>.</p>
<pre class="prettyprint">
< winner Year="1999" >Manchester Utd.< /winner >
</pre>
<p><br/></p>
<p>We can nest the all these to make a hierarchy of xml elements:</p>
<pre class="prettyprint">
XElement root = new XElement("winners",
                              new XElement("winner",
                                   new XElement("Name", "Barcelona"),
                                   new XElement("Country", "Spania"),
                                   new XElement("Year", 2006)
                              ),
                              new XElement("winner",
                                   new XElement("Name", "Liverpool"),
                                   new XElement("Country", "Anglia"),
                                   new XElement("Year", 2005)
                              )
                );
</pre>
<p><br/></p>
<p>Of course, the XML elements don&#8217;t have to be created like that. They can be dynamically created. One way is using methods like Add, AddFirst, RemoveNodes, etc., methods from the XContainer class.</p>
<pre class="prettyprint">
IEnumerable< Winner > winners = UCL.GetWinners();
XElement root = new XElement("winners");

foreach (Winner w in winners)
{
      root.Add(new XElement("winner",
                             new XElement("Name", w.Name),
                             new XElement("Country", w.Country),
                             new XElement("Year", w.Year)));
}
</pre>
<p><br/></p>
<p>And we can write this to a file with:</p>
<pre class="prettyprint">
Root.Save("winners.xml");
</pre>
<p><br/></p>
<p>However, LINQ to XML offers a better way to generate XML content.</p>
<pre class="prettyprint">
IEnumerable< Winner > winners = UCL.GetWinners();

XElement root = new XElement("winners",
                    from w in winners
                    select new XElement("winner",
                                        new XElement("Name", w.Name),
                                        new XElement("Country", w.Country),
                                        new XElement("Year", w.Year)));
</pre>
<p>The result in this case is the same as above.</p>
<p>XElements has several overloads for saving its content to a file:</p>
<pre class="prettyprint">
public void Save(string fileName);
public void Save(TextWriter textWriter);
public void Save(XmlWriter writer);
public void Save(string fileName, bool preserveWhitespace);
public void Save(TextWriter textWriter, bool preserveWhitespace);
</pre>
<p></br/></p>
<p>On the other hand, XElement offers several overloaded static methods for loading content from XML files:</p>
<pre class="prettyprint">
public static XElement Load(string uri);
public static XElement Load(TextReader textReader);
public static XElement Load(XmlReader reader);
public static XElement Load(string uri, bool preserveWhitespace);
public static XElement Load(TextReader textReader, bool preserveWhitespace);
public static XElement Parse(string text);
public static XElement Parse(string text, bool preserveWhitespace);
</pre>
<p><br/></p>
<p>The following code loads the content of the file winners.xml and prints it in the console.</p>
<pre class="prettyprint">
XElement root = XElement.Load("winners.xml");
Console.WriteLine(root.ToString());
</pre>
<p><br/></p>
<p>Considering that we have in winners.xml the list of UEL winners, we can load the content of this XML file and create Winner objects:</p>
<pre class="prettyprint">
IEnumerable< Winner > winners =
             from e in XElement.Load("winners.xml").Elements("winner")
             select new Winner
                    {
                         Name = (string)e.Element("Name"),
                         Country = (string)e.Element("Country"),
                         Year = (int)e.Element("Year")
                    };

foreach (Winner w in winners)
{
     Console.WriteLine("{0} {1}, {2}", w.Year, w.Name, w.Country);
}
</pre>
<p><br/></p>
<p>XElement.Load() creates an XElement containing all the elements in the file. Elements() returns only the children called <i>winner</i> (in our case all the children elements of the root). After that we project Winners created by accessing the children of element &#8220;winner&#8221; in the XML file. The output is</p>
<pre class="prettyprint">
2006 Barcelona, Spania
2005 Liverpool, Anglia
2004 FC Porto, Portugalia
2003 AC Milan, Italia
2002 Real Madrid, Spania
2001 Bayern Munchen, Germania
2000 Real Madrid, Spania
1999 Manchester Utd., Anglia
1998 Real Madrid, Spania
1997 Borussia Dortmund, Germania
1996 Juventus, Italia
1995 AFC Ajax, Olanda
1994 AC Milan, Italia
1993 Olympique de Marseille, Franta
</pre>
<p><br/></p>
<p>Now suppose you want to project only the names of the winners. In this case we could write:<br/></p>
<pre class="prettyprint">
var winners =
            from e in XElement.Load("winners.xml").Elements("winner")
            select (string)e.Element("Name");

foreach (var w in winners)
{
     Console.WriteLine("{0}", w);
}
</pre>
<p><br/></p>
<p>The ouput of the program is:</p>
<pre class="prettyprint">
Barcelona
Liverpool
FC Porto
AC Milan
Real Madrid
Bayern Munchen
Real Madrid
Manchester Utd.
Real Madrid
Borussia Dortmund
Juventus
AFC Ajax
AC Milan
Olympique de Marseille
</pre>
<p><br/></p>
<p>This output however lists a team multiple times. If we want to have these winners listed only once we could apply the Distinct operator on the result and select the winners only once:</p>
<pre class="prettyprint">
var winners =
         from e in XElement.Load("winners.xml").Elements("winner")
         select (string)e.Element("Name");

var winnersDistinct = Enumerable.Distinct(winners);

foreach (var w in winnersDistinct)
{
    Console.WriteLine("{0}", w);
}
</pre>
<p><br/></p>
<p>The new output would be</p>
<pre class="prettyprint">
Barcelona
Liverpool
FC Porto
AC Milan
Real Madrid
Bayern Munchen
Manchester Utd.
Borussia Dortmund
Juventus
AFC Ajax
Olympique de Marseille
</pre>
<p><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2007/04/17/linq-to-xml/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>yield keyword and lazy evaluation in C#</title>
		<link>http://mariusbancila.ro/blog/2007/04/13/yield-keyword-an-lazy-evaluation-in-c/</link>
		<comments>http://mariusbancila.ro/blog/2007/04/13/yield-keyword-an-lazy-evaluation-in-c/#comments</comments>
		<pubDate>Fri, 13 Apr 2007 08:09:32 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=30</guid>
		<description><![CDATA[yield is a new contextual keyword introduced to C# 2.0, vital for lazy evaluation and the performance of queries in LINQ. Being a contextual keyword means that yield can be used as a variable name in C# without any problem. When put before return it becomes a keyword. yield allows one enumerable class to be [...]]]></description>
			<content:encoded><![CDATA[<p><i>yield</i> is a new contextual keyword introduced to C# 2.0, vital for lazy evaluation and the performance of queries in LINQ. Being a contextual keyword means that <i>yield</i> can be used as a variable name in C# without any problem. When put before return it becomes a keyword.</p>
<p><i>yield</i> allows one enumerable class to be implemented in terms of another. This enables the delay of execution of queries until the latest possible moment, skipping the generation of intermediate results that would drastically reduce poerformance. The query operators in LINQ operate on sequence. The result of a query is often another sequence. Lazy evaluation means that until you iterate over the result of the query, the source of the query is not iterated.</p>
<p>To show you how <i>yield</i> works, let&#8217;s consider the same class I used in my last <a href="http://mariusbancila.ro/blog/?p=27">post</a>, Winner.</p>
<pre class="prettyprint">
public class Winner
{
    string _name;
    string _country;
    int _year;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    public string Country
    {
        get { return _country; }
        set { _country = value; }
    }
    public int Year
    {
        get { return _year; }
        set { _year = value; }
    }
    public Winner(string name, string country, int year)
    {
       _name = name;
       _country = country;
       _year = year;
    }
}
</pre>
<p><br/></p>
<p>and create a class WinnerDB, that contains a list of UEFA Champion League winners. This class implements IEnumerable and returns an enumerator, WinnerEnumerator, to be able to iterate over the winners.
<pre class="prettyprint">
    public class WinnerEnumerator : IEnumerator
    {
        int pos = -1;
        private Winner[] _winners;
        public WinnerEnumerator(Winner[] winners)
        {
            _winners = winners;
        }

        public void Reset()
        {
            pos = -1;
        }

        public bool MoveNext()
        {
            pos++;
            return (pos < _winners.Length);
        }

        public object Current
        {
            get
            {
                try
                {
                    return _winners[pos];

                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }
    }

    public class WinnersDB : IEnumerable
    {
        private Winner[] _winners;
        public WinnersDB()
        {
            _winners = new Winner[]
            {
                new Winner("Barcelona", "Spain", 2006),
                new Winner("Liverpool", "England", 2005),
                new Winner("FC Porto", "Portugal", 2004),
                new Winner("AC Milan", "Italy", 2003),
                new Winner("Real Madrid", "Spain", 2002),
                new Winner("Bayern Munchen", "Germany", 2001),
                new Winner("Real Madrid", "Spain", 2000),
                new Winner("Manchester Utd.", "England", 1999),
                new Winner("Real Madrid", "Spain", 1998),
                new Winner("Olimpique Marseille", "France", 1993),
            };
        }

        public IEnumerator GetEnumerator()
        {
            return new WinnerEnumerator(_winners);
        }
    }
</pre>
<p><br/></p>
<p>The usage of this class would look like this:</p>
<pre class="prettyprint">
    class Program
    {
        static void Main(string[] args)
        {
            WinnersDB db = new WinnersDB();
            foreach (Winner w in db)
            {
                Console.WriteLine("{0}\t{1}, {2}",
                    w.Year, w.Name, w.Country);
            }
        }
    }
</pre>
<p><br/></p>
<p>and the output of the program</p>
<pre class="prettyprint">
2006    Barcelona, Spain
2005    Liverpool, England
2004    FC Porto, Portugal
2003    AC Milan, Italy
2002    Real Madrid, Spain
2001    Bayern Munchen, Germany
2000    Real Madrid, Spain
1999    Manchester Utd., England
1998    Real Madrid, Spain
1993    Olimpique Marseille, France
</pre>
<p><br/></p>
<p>So far so good. But with <i>yield</i>, you can let the compiler do all that stuff for you. When you use <i>yield</i>, the compiler generates an enumerator that keeps the current state of the iteration.</p>
<pre class="prettyprint">
class Program
{
    public static IEnumerable<Winner> WinnersDB()
    {
        Winner [] winners = new Winner[]
        {
                new Winner("Barcelona", "Spain", 2006),
                new Winner("Liverpool", "England", 2005),
                new Winner("FC Porto", "Portugal", 2004),
                new Winner("AC Milan", "Italy", 2003),
                new Winner("Real Madrid", "Spain", 2002),
                new Winner("Bayern Munchen", "Germany", 2001),
                new Winner("Real Madrid", "Spain", 2000),
                new Winner("Manchester Utd.", "England", 1999),
                new Winner("Real Madrid", "Spain", 1998),
                new Winner("Olimpique Marseille", "France", 1993),
        };

        foreach (Winner w in winners)
        {
            yield return w;
        }
    }

    static void Main(string[] args)
    {
        foreach (Winner w in WinnersDB())
        {
            Console.WriteLine("{0}\t{1}, {2}",
                w.Year, w.Name, w.Country);
        }
    }
}
</pre>
<p><br/></p>
<p>Running this code will produce the same output as the previous one, except that the implementation is much simpler. Perhaps the example is not the best, but should give you a hint of the use of the <i>yield</i> keyword. To see that the source is actually iterated only when the result is iterated, we can modify the WinnersDB method to print a message in the console:</p>
<pre class="prettyprint">
foreach (Winner w in winners)
{
    Console.WriteLine("yield: {0} {1}, {2}", w.Year, w.Name, w.Country);
    yield return w;
}
</pre>
<p><br/></p>
<p>In this case, the output looks like this:
<pre class="prettyprint">
yield: 2006 Barcelona, Spain
2006    Barcelona, Spain
yield: 2005 Liverpool, England
2005    Liverpool, England
yield: 2004 FC Porto, Portugal
2004    FC Porto, Portugal
yield: 2003 AC Milan, Italy
2003    AC Milan, Italy
yield: 2002 Real Madrid, Spain
2002    Real Madrid, Spain
yield: 2001 Bayern Munchen, Germany
2001    Bayern Munchen, Germany
yield: 2000 Real Madrid, Spain
2000    Real Madrid, Spain
yield: 1999 Manchester Utd., England
1999    Manchester Utd., England
yield: 1998 Real Madrid, Spain
1998    Real Madrid, Spain
yield: 1993 Olimpique Marseille, France
1993    Olimpique Marseille, France
</pre>
<p><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2007/04/13/yield-keyword-an-lazy-evaluation-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>LINQ: declarative and functional syntax</title>
		<link>http://mariusbancila.ro/blog/2007/04/09/linq-declarative-and-functional-syntax/</link>
		<comments>http://mariusbancila.ro/blog/2007/04/09/linq-declarative-and-functional-syntax/#comments</comments>
		<pubDate>Mon, 09 Apr 2007 19:48:31 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=27</guid>
		<description><![CDATA[In my last post about LINQ I shown you an example about how to use the language integrated query to select information about directories. In this post I&#8217;ll get more into the syntax and show you something about the functional querying style. My examples will focus on displaying information about UEFA Champions Leage winners. Thus, [...]]]></description>
			<content:encoded><![CDATA[<p>In my last post about LINQ I shown you an example about how to use the language integrated query to select information about directories. In this post I&#8217;ll get more into the syntax and show you something about the functional querying style.</p>
<p>My examples will focus on displaying information about UEFA Champions Leage winners. Thus, I have created a class called Winner that looks this this:</p>
<pre class="prettyprint">
class Winner
{
    string  _name;
    string  _country;
    int     _year;

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }
    public string Countryr
    {
        get { return _country; }
        set { _country = value; }
    }

    public int Year
    {
        get { return _year; }
        set { _year = value; }
    }

    public Winner(string name, string country, int year)
    {
        _name = name;
        _country = country;
        _year = year;
    }
};
</pre>
<p><br/></p>
<p>Also I have created a utility class that returns a list (incomplete) of UCL winners:</p>
<pre class="prettyprint">
class UCL
{
    public static IEnumerable<Winner> GetWinners()
    {
        Winner [] winners =
        {
            new Winner("Barcelona", "Spain", 2006),
            new Winner("Liverpool", "England", 2005),
            new Winner("FC Porto", "Portugal", 2004),
            new Winner("AC Milan", "Italy", 2003),
            new Winner("Real Madrid", "Spain", 2002),
            new Winner("Bayern Munchen", "Germany", 2001),
            new Winner("Real Madrid", "Spain", 2000),
            new Winner("Manchester Utd.", "England", 1999),
            new Winner("Real Madrid", "Spain", 1998),
            new Winner("Olimpique Marseille", "France", 1993),
        };

        return winners;
    }
};
</pre>
<p><br/></p>
<p>Now, let&#8217;s see how we could display all this info ascending by the year of winning:</p>
<pre class="prettyprint">
IEnumerable<Winner> winners = UCL.GetWinners();
var result = from w in winners
             orderby w.Year
             select w;

foreach (var w in result)
{
    Console.WriteLine("{0}\t{1}, {2}",
            w.Year, w.Name, w.Country);
}
</pre>
<p><br/></p>
<p>That lists the following:</p>
<pre class="prettyprint">
1993    Olimpique Marseille, France
1998    Real Madrid, Spain
1999    Manchester Utd., England
2000    Real Madrid, Spain
2001    Bayern Munchen, Germany
2002    Real Madrid, Spain
2003    AC Milan, Italy
2004    FC Porto, Portugal
2005    Liverpool, England
2006    Barcelona, Spain
</pre>
<p><br/></p>
<p>This SQL-like syntax is however only a &#8220;shell&#8221; over the functional syntax. It&#8217;s just like with the foreach statement. To be able to iterate with foreach, the collection must implement IEnumerable, which has a method that returns a class that implements IEnumerator. What the compiler is doing when using foreach is calling GetEnumerator to get an iterator, and then Reset() on it, and inserts a while(iterator.MoveNext()), using Current to access the current object from the collection. The same happens here with the declarative query syntax. </p>
<p>Now, let&#8217;s suppose we want to list only the winners from England. What we have to do is adding a filtering:</p>
<pre class="prettyprint">
var result = from w in winners
             orderby w.Year
             where w.Country == "England"
             select w;
</pre>
<p><br/></p>
<p>What I wrote above is actually the same with:</p>
<pre class="prettyprint">
var result = winners.
               OrderBy(w => w.Year).
               Where(w => w.Country == "England").
               Select(w => w);
</pre>
<p><br/></p>
<p>Here we used the operators OrderBy, Where and Select. These are two of the query operators that allow you to perform filtering, projection and key extraction. These are built of the concept of Lambda expression, which are similar to the CLR delegates. We could rewrite the last query list this:</p>
<pre class="prettyprint">
Func<Winner, bool> filter = w => w.Country == "England";
Func<Winner, int> criteria = w => w.Year;
Func<Winner, Winner> project = w => w;

var result = winners.OrderBy(criteria).Where(filter).Select(project);
</pre>
<p><br/></p>
<p>OrderBy and OrderByDescending are operators that impose a partial order over the keys. Operators ThenBy and ThenByDescending are used to apply additional sorting criteria by only on sorted sequences (SortedSequence<T>).</p>
<p>Where is used to exclude items from the collection.</p>
<p>Select and SelectMany are operators for projecting only those fields or info that is wanted.</p>
<p>Now, let&#8217;s try something more complicated: grouping the winners by country, and inside each group ascending by the winning year. In declarative syntax that would be like this:</p>
<pre class="prettyprint">
var result = from w in winners
             orderby w.Year
             group w.Name by w.Country into groups
             orderby groups.Key
             select groups;

foreach (var w in result)
{
     Console.WriteLine("\n{0}", w.Key);

     foreach (var e in w)
     {
        Console.WriteLine("{0}", e);
     }
}
</pre>
<p><br/></p>
<pre class="prettyprint">
Enagland
Manchester Utd.
Liverpool

France
Olimpique Marseille

Germany
Bayern Munchen

Italy
AC Milan

Portugal
FC Porto

Spain
Real Madrid
Real Madrid
Real Madrid
Barcelona
</pre>
<p><br/></p>
<p>In functional programming syntax, the same query is written as:</p>
<pre class="prettyprint">
var result = winners.
                  OrderByDescending(w => w.Year).
                  GroupBy(w => w.Country, w => w.Name).
                  OrderBy(w => w.Key).
                  Select(w => w);
</pre>
<p><br/><br />
The GroupBy operator imposes a partitioning over a sequence of values based on a key extraction function. It returns a sequence of Grouping values, which contains both the key as well as the group of values mapped to the key. The interface of Grouping is:</p>
<pre class="prettyprint">
public sealed class Grouping<K, T>{
  public Grouping(K key, IEnumerable<T> group);
  public Grouping();
  public K Key {get; set;}
  public IEnumerable<T> Group {get; set;}
}
</pre>
<p><br/></p>
<p>You may wonder why the declarative syntax starts with the from clause. The SQL language has a problem, i.e. the order of clauses is not natural. Select is the first by at the time of selecting, you don&#8217;t know where do you select from. The from clause is naturally the first one, and this was rectified in LINQ. You always have to put from as the first clause in a query (when using the declarative syntax). In the functional syntax you can see you have to apply the operators on a collection, a sequence of items (in our case winners). That is the functional equivalent of from.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2007/04/09/linq-declarative-and-functional-syntax/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ example: listing directories</title>
		<link>http://mariusbancila.ro/blog/2007/03/27/use-linq-to-list-directories/</link>
		<comments>http://mariusbancila.ro/blog/2007/03/27/use-linq-to-list-directories/#comments</comments>
		<pubDate>Tue, 27 Mar 2007 19:42:38 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=19</guid>
		<description><![CDATA[LINQ is a valuable feature for database and XML programming, but not only. Basically, you can use LINQ with everything that returns an IEnumerable. Here is an example, when I want to list the directories of a parent directory, in alfabetical order, and grouped by the file attributes (first all that have only the flag [...]]]></description>
			<content:encoded><![CDATA[<p>LINQ is a valuable feature for database and XML programming, but not only. Basically, you can use LINQ with everything that returns an IEnumerable. Here is an example, when I want to list the directories of a parent directory, in alfabetical order, and grouped by the file attributes (first all that have only the flag <em>Directory</em> set, then those that have both <em>ReadOnly</em> and <em>Directory</em>, etc.).</p>
<p>First, let&#8217;s try how you would put this clasically in C# 2.0. Basically you need these:</p>
<ul>
<li>obtain a list of directory names</li>
<li>create a sorted dictionary with the key representing the file attributes, and the value a list of directories</li>
<li>iterate over the list of names and create a DirectoryName object</li>
<li>add the object to the list corresponding to the key represented by the directory attributes</li>
<li>iterate over the dictionary and print its content</li>
</ul>
<p>The code I wrote for that looks like this:</p>
<pre class="prettyprint">
void ClassicList(string path)
{
    string [] entries = System.IO.Directory.GetDirectories(path);

    SortedDictionary<FileAttributes, List<DirectoryInfo>> dic =
        new SortedDictionary<FileAttributes, List<DirectoryInfo>>();

    foreach (string entry in entries)
    {
        DirectoryInfo dir = new DirectoryInfo(entry);

        try
        {
            dic[dir.Attributes].Add(dir);
        }
        catch (KeyNotFoundException)
        {
            dic.Add(dir.Attributes, new List<DirectoryInfo>());
            dic[dir.Attributes].Add(dir);
        }
    }

    foreach (KeyValuePair<FileAttributes, List<DirectoryInfo>> group in dic)
    {
        Console.WriteLine("Directories with attributes: {0}", group.Key);

        foreach (DirectoryInfo dir in group.Value)
            Console.WriteLine("  {0}", dir.Name);
    }
}
</pre>
<p><br/></p>
<p>With LINQ, things get much simpler, as you no longer need to create a dictionary. You can apply SQL-like queries on objects. What you have to do is:</p>
<ul>
<li>obtain a list of directory names</li>
<li>create a query to select the directories and group them according to their attributes</li>
<li>iterate over the result and print the its content</li>
</ul>
<p>This is how it looks like:</p>
<pre class="prettyprint">
void LinqList(string path)
{
    string[] entries = System.IO.Directory.GetDirectories(path);

    var result = from dir in
                     from e in entries select new DirectoryInfo(e)
                 orderby dir.Name
                 group dir by dir.Attributes into dirGroups
                 orderby dirGroups.Key
                 select dirGroups;

    foreach (var group in result)
    {
        Console.WriteLine("Directories with attributes: {0}", group.Key);

        foreach (var dir in group)
            Console.WriteLine("  {0}", dir.Name);
    }
}
</pre>
<p><br/></p>
<p>Let&#8217;s take the querry line by line and see what it does:</p>
<ul>
<li>from dir in from e in entries select new DirectoryInfo(e)creates a DirectoryInfo for each element of entries and uses the resulted array as source</li>
<li>orderby dir.Nameorders the DirectoryInfo array by the name of the directories</li>
<li>group dir by dir.Attributes into dirGroupsgroups the directories by their attributes into dirGroups</li>
<li>orderby dirGroups.Keyorders the group by the key</li>
<li>select dirGroupsselects the groups</li>
</ul>
<p>And that&#8217;s all. You don&#8217;t have to struggle with creating dictionaries, maintaining the correct sorting and so on. You can do all of that with a simple query.</p>
<p>The following listing shows a second query that displays the directories ascending by their creation time, and for each directory the name, creation time and attributes are listed. The code also exemplifies the use of anonymous types, and the inference of the type from the assigned value, concepts new in C# 3.0:</p>
<pre class="prettyprint">
void LinqList2(string path)
{
    string[] entries = System.IO.Directory.GetDirectories(path);

    var result = from dir in
                     from e in entries select new DirectoryInfo(e)
                 orderby dir.CreationTime
                 select new {
                            Name = dir.Name,
                            Attr = dir.Attributes,
                            Creation = dir.CreationTime };

    foreach(var item in result)
    {
        Console.WriteLine("{0}\n\t{1}\t{2}",
                          item.Name, item.Creation, item.Attr);
    }
}
</pre>
<p><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2007/03/27/use-linq-to-list-directories/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>LINQ presentation</title>
		<link>http://mariusbancila.ro/blog/2007/03/18/linq-presentation/</link>
		<comments>http://mariusbancila.ro/blog/2007/03/18/linq-presentation/#comments</comments>
		<pubDate>Sun, 18 Mar 2007 22:09:58 +0000</pubDate>
		<dc:creator>Marius Bancila</dc:creator>
				<category><![CDATA[LINQ]]></category>
		<category><![CDATA[MVP]]></category>

		<guid isPermaLink="false">http://mariusbancila.ro/blog/?p=9</guid>
		<description><![CDATA[Anders Hejlsberg, creator of Turbo Pascal and C#, delivered a great presentation on LINQ on Tuesday. This was actually my first contact with LINQ (which stands for Language INtegrated Query), but it makes me envy the C# and VB.NET programmers, because these are the only two languages that support it. LINQ defines a set of general-purpose [...]]]></description>
			<content:encoded><![CDATA[<p>Anders Hejlsberg, creator of Turbo Pascal and C#, delivered a great presentation on LINQ on Tuesday. This was actually my first contact with LINQ (which stands for Language INtegrated Query), but it makes me envy the C# and VB.NET programmers, because these are the only two languages that support it. LINQ defines a set of general-purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language. It basically introduces SQL-like queries as first citizens of C# and VB.NET.</p>
<p> <img title="Andres Hejlsberg at the MVP Global Summit 2007" alt="Andres Hejlsberg at the MVP Global Summit 2007" src="http://mariusbancila.ro/blog/wp-content/uploads/2007/03/andres_hejlsberg.jpg" align="middle" /></p>
<p>A very simple sample provided by Don Box and Anders Hejlsberg in their article &#8220;The LINQ Project&#8221; at MSDN (<a href="http://msdn2.microsoft.com/en-us/library/aa479865.aspx">http://msdn2.microsoft.com/en-us/library/aa479865.aspx</a>) shows a query on objects in C#:</p>
<pre class="prettyprint">
using System;
using System.Query;
using System.Collections.Generic;

class app {
  static void Main() {
    string[] names = { "Burke", "Connor", "Frank",
                       "Everett", "Albert", "George",
                       "Harris", "David" };

    IEnumerable<string> expr = from s in names
                               where s.Length == 5
                               orderby s
                               select s.ToUpper();

    foreach (string item in expr)
      Console.WriteLine(item);
  }
}
</pre><br />
The output of the program being:</p>
<pre class="prettyprint">
BURKE
FRANK
DAVID
</pre><br />
Procedural languages, that express both <em>what</em> to do and <em>how</em> to do, have reached a point where there is nothing more to enhance. Removing the "how" part of the equation seems to be the next direction in the development of such languages. One of these cases is represented by the LINQ project, which simply makes C# and VB.NET more powerful.</p>
]]></content:encoded>
			<wfw:commentRss>http://mariusbancila.ro/blog/2007/03/18/linq-presentation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

