NuGet has recently added support for native projects. This simplifies a lot deployment of native libraries. Even though cpplinq is not a big library (in fact is just a header file) I have created a NuGet package so that you are able to automatically add it to your project.

Here is what you have to do.

  1. Make sure you have NuGet 2.5 or newer, otherwise the NuGet package manager won’t show up in your VC++ projects.
  2. In the context menu for your project choose Manage NuGet Packages…
    cpplinqdemo1
  3. Search for cpplinq and install the package.
    cpplinqdemo2
  4. Include the cpplinq.hpp header and start using the library. Here is a sample to test that everything is all right.

Notice that all the settings for library (such as adding the proper entry for the include directories or defining NOMINMAX so that min and max macros will not be defined for the project) are automatically performed, so you can focus on coding.

, , , , , , , Hits for this post: 40649 .

cpplinq: set operators

In the previous posts I introduced cpplinq, a C++ template library that provides .NET-like query operators for sequences of objects in C++11. In this third installment I will discuss the set operators the library provides.

There are four set operators: distinct, union_with (called so because union is a keyword in C++), intersect_with (suffix _with is for consistency with the union operator) and except. These operators should be pretty straight forward: distinct eliminates the duplicate elements from a sequence, yielding a new sequence with only the distinct elements (in the order their original order), union_with produces the set union of two sequences, intersect_with produces the set intersection of two sequences and except produces the set difference of two sequences.

Before seeing some examples, it worth nothing that all these operators delay the traversal of the sequences until the resulting object is enumerated.

Let’s see some examples:

You can learn more about these operators (and the others that are implemented) by reading the cpplinq query operators documentation.

, , , , , Hits for this post: 30071 .

cpplinq: An introduction

cpplinq is a C++ template library that provides .NET-like query operators for sequences of objects in C++11. cpplinq is an open-source library that works both with VC++ compilers (2010 and 2012) and gcc (4.7.0 is the version used for unit tests). The library supports most of the .NET query operators and is extendable with additional operators that can suite some particular use. If you’re not familiar with .NET query operators, this article, http://msdn.microsoft.com/en-us/library/bb394939.aspx, lists and explain them.

The light-weighted library consists of a series of template classes and helper methods, provided in a single header under the namespace cpplinq.

This is a short introduction to the library. More posts will follow. Let’s see some examples.

The following code retrieves all the prime numbers from an array.

A slightly variation produces a sequence of first N prime numbers and transforms them into strings.

The next sample retrieves all the orders from a customer.

Callinq print_orders_by_cust() with argument 1 would print:

On the other hand, if you want to print the last order from a particular customer, the function above would change to something like this:

Calling print_last_order_for_customer() with argument 1 would print:

Hopefully this provides a quick view over the capabilities of the library. In following posts I will show more examples and discuss some of the query operators. To learn more about the library see the following articles:

, , , , , Hits for this post: 36159 .

LINQ to SQL

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, 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

Considering the known Winner class from the previous posts,

Decorating it with Table and column like this

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.

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:

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:

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’t have to call directly GetTable<>().

The PrintWinnes function would have to change to:

Only querying the database is not enough. DataContext also allow us to submit changes to the database.

The following function shows how to add a winner to the table Winners:

If you want for instance to remove all the winners from Spain, we can do the following:

, , , Hits for this post: 42267 .

LINQ to XML

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.

In the namespace you can find classes such as XNode, XElement, XAttribute, XText, etc.

XElement implements an XML element. It has several constructor. The following snippet constructs an empty element called winner.

The output is

Overloaded constructor can take additional parameters. If we pass a string:

We get:

We can also pass an XAttribute

Or

In this case the winner element will have an attribute called Year having the value 1999, and the text of the element will be Manchester Utd..

We can nest the all these to make a hierarchy of xml elements:

Of course, the XML elements don’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.

And we can write this to a file with:

However, LINQ to XML offers a better way to generate XML content.

The result in this case is the same as above.

XElements has several overloads for saving its content to a file:

On the other hand, XElement offers several overloaded static methods for loading content from XML files:

The following code loads the content of the file winners.xml and prints it in the console.

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:

XElement.Load() creates an XElement containing all the elements in the file. Elements() returns only the children called winner (in our case all the children elements of the root). After that we project Winners created by accessing the children of element “winner” in the XML file. The output is

Now suppose you want to project only the names of the winners. In this case we could write:

The ouput of the program is:

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:

The new output would be

, Hits for this post: 37404 .

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 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.

To show you how yield works, let’s consider the same class I used in my last post, Winner.

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.

The usage of this class would look like this:

and the output of the program

So far so good. But with yield, you can let the compiler do all that stuff for you. When you use yield, the compiler generates an enumerator that keeps the current state of the iteration.

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 yield 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:

In this case, the output looks like this:

, , Hits for this post: 55895 .