Linq for C++


The benefits of SQL-like declarative syntax for imperative programming languages like C# is [well documented]( Linq as it is known in C# has been implemented by more than one team in C++. The main advantages are

      Improved Readablity
      Declarative Syntax
      Less coding (usually)

There are at least four implementations of Linq for C++:


Codeplex in turn lists other attempts:

CPP Linq from Berrysoft

Here I consider Berrysoft, mostly because the library implementation was easy to understand

Consider the following code:

read_lines(cin) >>
   where ([] (string const& str) {
        return str.find("include") != string::npos;
   }) >>

The code filters out all lines not containing the string “include”. Grep or Awk can do the same thing in one line of code. But the advantage of this code is that the data can be shaped as shown below:

struct trade{
  string symbol;
  bool is_buy;
  date purchase_date;
  double cost;
auto trades {read_lines(cin) >>
   select ([] (string const& str) {
      auto e{str>>split(',')>>to_vector()};
      trade t;
      t.symbol = e[5];
      t.is_buy = e[4]=="B";
      istringstream{e[3]} >>
        parse("%d/%m/%Y", t.purchase_date);
      t.cost = strtod(e[8].c_str((), nullptr);
      return t;
   }) >> to_vector()};

At this point we have all the trades stored in a container and from here on we get the full power of C++. As an aside [Howard Hinant’s]( date library is used in the above code.

About The Sunday Programmer

Joe is an experienced C++/C# developer on Windows. Currently looking out for an opening in C/C++ on Windows or Linux.
This entry was posted in C++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s