Dot Net Fluke: Getting by on C# for iSeries RPG Developers

Useful tutorials on C# and .NET for RPG iSeries AS/400 developers. Brought to you from the folks at AranRock Consulting

8/7/08

How to video: Access data on iSeries using ADO.NET

Here is a super simplified video example of a C# application reading from a table on an iSeries. It uses the IBM .net managed provider (See Different ways to access iSeries data and this) . You have this  if you have IBM Client Access. If not, download the technology preview here. Sound problem? jiggle the player control if the sound goes out (I'm trying out demo utility software let me know what one you use.)
.

To view the video click here.

To download the project used in the video, click here.

Subscribe to DotNetFluke to receive weekly useful tips for integrating .NET with the iSeries.
If you have any iSeries/.NET integrations questions or suggestions for articles email me at cbyrne+blog@AranRock.com

Labels: , , , , ,

8/5/08

Converting RPG code to C# automatically?

What if you could take  your RPG programs and hey presto! have them converted into .NET and instantly sell your product to the rest of the world.   This would be a boon to AS/400 vendors locked into the small(ish) AS/400 market.   The advantage is that the original product is likely  a mature business proven system which can provide a critical edge against the deluge of competition once in the new windows space.  While  webfacing does provide a web front end to applications and is great for hosted models it does not help customers who are windows only and want windows only software.

Granted companies need to migrate on the competition level . However, all the supposed advantages such as performance, cost savings, availability of talent etc sounds hollow to long time AS/400 owners. Anecdotally we know that the uptime for the AS/400 is absolutely stunning compared to windows.  It's super stable and extremely reliable. At windows only shops instead of maintaining one iSeries server  and a handful of windows server you end  up maintaining 20-30 windows servers for a small organization.  But like I said, it's about getting your product out to a bigger market.
A big issue with migration products is that often your migrated solution will not be able to operate without them. Yikes! 

I'll be doing a review of these migration products once I get my hands on them but in the meantime here's an overview. Click the title to go to the product website.

TranSoft ML-Impact 
Well, the boys and girls at TranSoft claim that they can convert your old F-specs, c-specs to .NET .   I would love to see the code generated (post a sample  in comments pleez). They claim that CL and RPG will be converted to C#. Not only that they can take the DB2 tables and migrate them to SQL server. Not everything can be converted directly of course and the end result looks much like a 5250 application.
Without having the product available to me I can't give it the thumbs up or down  but if you have any experience with this tool, please drop a comment.

ADC Austin
Remember Synon? The hot product of 20 years ago is now trying to be cool.  They have jiggered a way to migrate from CA2E (Synon)  to Plex which uses .NET.   Sounds complicated. If you've tried it, drop me a line.

ASNA Monarch and AVR for .NET
ASNA monarch is a code converter that  creates RPG for .NET while AVR is a Visual Studio add-in that allows RPG  for .NET (an ASNA creation) development and compiles as a .net app.   Seems like these two products have the same product base.  The only feedback I've seen on this product is that there is no code completion, no automatic layout and ctl-z doesn't work.  Your comments pls.

Lansa Ramp and the rest
There are a bunch of other sticky migration tools out there that are designed to keep you using their applications. While the products above are somewhat sticky you can still migrate off them.  Products like the Lansa Ramp platform is a staged migration solution that requires you to develop a an application framework using their tools, prototype it, then recreate your screens in that framework. However the end product is a Lansa architecture that you have to stick with for the rest of eternity. 

Labels: , , ,

3/18/08

C# Subfile - iSeries data in a C# Grid -2 no coding (with Video)

Well almost no coding.

If you look at my previous post where I showed how to code a grid in C# using data from the iSeries we manually coded the grid, the data set and the connection. This example accomplishes the same result except you'll be done in under 5 minutes!  It uses the IDE to build the grid, data set, adapter, connection and SQL command.

The video also shows how to add in the iSeries .net data components to your Visual Studio toolbox.
This post easier shown than discussed - so check out the following video.
play

Steps

  1. Create a windows form application project
  2. Add in the IBM dll to your references
  3. Add in the IBM data tools to your toolbox using Tools, Choose Toolbox items and filter 'idb2'
  4. Add a basic grid to your form
  5. Drag the iDB2Connection, IDB2Command, iDB2DataAdapter and a data set to your form
  6. Configure each by right clicking and selecting properties
  7. Double click outside the grid to bring up the code for the Load method of the form.
  8. Add in the following code
    iDB2DataAdapter1.Fill(dataSet1);
    dataGrid1.DataMember = dataSet1.Tables[0].TableName;
  9. Run the program!

Labels: , , , , , ,

3/17/08

C# Subfile - Display an iSeries table in a Grid

We're all used to subfiles on the iSeries. Who can fondly recall many a debate over page by page vs. load all subfile?   How do you create the equivalent of a subfile in .Net?

Easy.

images

Download the visual studio project from here.

subfile

Here's a basic example to get started. The Visual Studio IDE can actually do a lot of the work for you. You can even create a grid (read subfile) with just one or two lines of code. (Post to come)  However, it's more prudent to begin with code you can understand rather than wading through what looks like binary spaghetti.

This example also introduces data sets and data tables. Data sets are just like data structures but without any definition and data tables are just like the field definitions of data structures -not to be confused with tables in databases. We use Data sets and data tables to disconnect from the data source. Connect to the data source, get the data, fill the data set with the data, disconnect from the data source and use the data set in lieu of the actual data. Another way to think of data sets is to think of them as a cache, bucket, container, plastic bag. See my earlier post on data sets for more info.

 

Steps

  1. Define your grid (i.e. subfile)
  2. Attach the grid to your form (VS creates one for you auto-)
  3. Create a data set to hold your data
  4. Create a data table to define the fields in the data set
  5. Add the data table to the data set
  6. Connect  to your iSeries
  7. Execute an SQL statement to read from a table
  8. Read each row and add to the data set
  9. Disconnect from the iSeries
  10. Attach the data set to the grid
  11. Display the grid

It sounds like a lot of work just to output data to a grid - and it is. Why bother with the data set and the table - can't I just write directly out the grid? Yes you can - but this example is here to show you not only how to display data in a grid from the iSeries but how to best manage that data as well. A Data Set will help you do that. 
It is true that there are much simpler approaches on the iSeries but that comes at a price. Once you get out of the db2 and green screen box things get quite tricky on the As/400.  .Net is more complicated yes but its complexity comes from flexibility.

iSeries prerequisites:

The table on the iSeries in this example is called customers. Create it in library QGPL
create the table in DDS or go into SQL by typing 'strsql' in the iSeries command prompt and create the table as follows:

CREATE TABLE QGPL/CUSTOMERS (NAME CHAR (30 ) NOT NULL WITH DEFAULT,
BALANCE DEC (5 ) NOT NULL WITH DEFAULT)

Add records using the INSERT sql command, DBU or your favorite data editor on the iSeries

C# Code:

This is the code for the form. The 'Program.cs' in solution explorer is unchanged. Simply create a windows project, double click on the form that appears and replace all the code with the code below. Insert your iSeries IP address and make sure you have created the iSeries table as describe above or replace with your own ensuring that you correctly specify the columns.  

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using IBM.Data.DB2.iSeries; // Make sure you add this under 'References' in Solution Explorer
// You need the above reference as a dll which is part of iSeries client access.

namespace iSeries_Grid
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Define the grid size
            DataGrid subfile = new DataGrid();
            subfile.Location = new Point(0, 0);
            subfile.Size = new Size(400, 500);

            //Attach it to the form
            Controls.AddRange(new Control[] { subfile });


            // Create a DataSet to hold data from iSeries Table
            DataSet dataStructure = new DataSet();

            //Create a table to hold the iSeries data
            DataTable dt = new DataTable("Customers");
            dt.Columns.Add("Name");
            dt.Columns.Add("Balance");


            //Add the datatable to the data set
            dataStructure.Tables.Add(dt);

            // Open connection to the iSeries
            iDB2Connection conn = new iDB2Connection();
           conn.ConnectionString = "DataSource=192.168.0.1";

 // You can put "UserID=myuserid;Password=mypass" 
//
if you don't want to be prompted

// Create a command to select records from the customer table
iDB2Command command = new iDB2Command();
command.CommandText = "Select * from qgpl.customers";
command.Connection = conn;
// ties the command to the connection to the iSeries

conn.Open();

// Execute the sql statement. Get a Data Reader object
iDB2DataReader readFile = command.ExecuteReader();

// Read each row from the table and output the results into the data set

while (readFile.Read())
{
// Create a row to hold data
DataRow datarow = dataStructure.Tables["customers"].NewRow();

datarow["Name"] = readFile.GetString(0);
datarow["Balance"] = readFile.GetiDB2Integer(1);

// add the row to the data table customer
dataStructure.Tables["customers"].Rows.Add(datarow);


}

// Clean up - Close connections
readFile.Close();
command.Dispose();
conn.Close();

// Attach the data set to the data grid
subfile.DataSource = dataStructure;
subfile.DataMember = dataStructure.Tables[0].TableName;



// Display the subfile
subfile.Show();


} // End of Method


} //End of Class

} // End of Namespace



 



This code is based on an example in the IBM .Net Redbook modified

for this post.

Labels: , , , , ,

3/16/08

Reading an iSeries table in C# (with video)

Here's another simple example of reading a table in C# from the iSeries.
vid  See the video for this here. 

images

   Download the Visual Studio Project here

As you can see (line 13)  all you need in the connection string is the IP address of your machine. If you don't include the log on parameters -UserID=myuser; Password=mypass, then you will be prompted for them by the iSeries.
You need to include the IBM .net provider in your 'References' in your Visual Studio project. It's located in the Client Access directory. If you don't have client access, then download the 'technology preview' from IBM for free.

   1:  using System;


   2:  using System.Collections.Generic;


   3:  using System.Text;


   4:  using IBM.Data.DB2.iSeries;


   5:   


   6:  namespace Prez_Rank


   7:  {


   8:      class Program


   9:      {


  10:          static void Main(string[] args)


  11:          {


  12:              iDB2Connection conn = new iDB2Connection();


  13:              conn.ConnectionString = "DataSource=192.168.0.1";


  14:              conn.Open();


  15:   


  16:              iDB2Command cmd = new iDB2Command();


  17:              cmd.CommandText = "Select * from colm.customers";


  18:              cmd.Connection = conn;


  19:   


  20:   


  21:   


  22:              iDB2DataReader dr= cmd.ExecuteReader();


  23:   


  24:              while (dr.Read())


  25:              {


  26:                  Console.WriteLine(dr.GetString(0));


  27:   


  28:              }


  29:              Console.ReadLine();


  30:   


  31:          }


  32:      }


  33:  }


Labels: , , , ,

3/5/08

RPG Variables vs C# Variables

In RPG we define variables in our 'D or C Specs.  We don't have to  uniquely declare character or numeric-  just the inclusion of a value in the decimal places column is enough. Leave it out and you just defined a character variable.
For the most part this is all you need to write 90% of business applications. There are other variable types such Binary, Graphic etc but these are encountered less often.
 

DName+++++++++++ETDsFrom+++To/L+++IDc.Keywords++

D NameofDog       S             24              
D Counter S 2 0
D Price S 5 2
D Datefield S D

Here's the equivalent in C#


String NameofDog;
int Counter;
decimal Price;
DateTime datefield;



The first thing that you will notice is that there is no length defined for the fields in C#. That's a great improvement over RPG where you usually explicitly declare length and end up in lots of trouble when a value gets chopped off when moved to a smaller field.

In C# there are way more value types than needed such as byte (for numbers 0-255), sbyte, short, long, float etc.





Common Value Types in C#


Int - integer - whole numbers (no decimals). Useful for counting.


string - holds alphanumeric values


bool - true or false (similar to indicators)


double any decimal up to 15 significant digits


decimal - any decimal up to 28 sig. digits



The variable declarations in RPG did not quite translate to C#. There is no Date value type in C#.  The statement ' DateTime datefield;' declares an object reference called datefield. How do I know this? Only because I know there is not value type of date in C#.  The fact that I am declaring an object called datefield just as I would a variable value brings up all sorts of interesting things about C# - mainly that objects are just another kind of variable. More on that later.



What about Operations on variables?


Let's add 1 to Counter in RPG and C#



RPG



Counter = Counter + 1;


C#


Counter = Counter + 1;



The code is the exact same in both!  There are other differences but we'll get operations in another post.




Lot's of free stuff inside


When you declare a variable in C# whether it is a value type like an integer or a 'reference' type like the DateTime object I created, along with the variable comes packaged  actions you might need on it.  In RPG if I want to convert my counter to a string variable, I would do the following.





RPG


Character = %char(Numeric); 



In C#, there is a method or function included in the variable when you declare it. The brackets indicate that ToString is a method.



Character = Numeric.ToString();



This is a fundamental and important aspect of C# - The actions you perform on variables and objects are often methods of that variable or object. If you want to trim the end of a string in C# you just say Character.Trim(); . Because you declared Character as a type String and String has all these methods now Character has them. There is no 'trim' opcode or expression. It's a method of string and when you declare a variable as a type string it gets all the methods belonging to string.

What's great about this is that you don't have to wait 10 years for IBM to come up with another op-code - you just write one yourself!  But, you may be asking, how do I know what method to use? There must be thousands. There are. However the Visual Studio IDE makes it simple and has a feature called intellisense - it fills out the statement as you type showing a drop down of all the methods and properties of an object or variable. Don't worry if this doesn't make a huge amount of sense right now. You'll get the hang of it with practice but it is one of those kind of mind-flips that is a big switch from Procedural RPG and Object Oriented C#.  It also makes sense. While RPG is an awesome language it has hit a stone wall. Creating lots of more opcodes or expressions is just going to make the language more complex. C# doesn't need lots of 'op-codes' - in fact there are about 77 in C# 2.0 and many you will never use. Most actions come from methods in classes.

Labels: , , , ,

1/26/08

RPG Subroutine = C# Method?

Someone asked me the other day if RPG subroutines are the same as C# methods.
The answer is yes - like C# static methods but RPG Procedures are even more similar to C# static methods.
The reason being is that while C# methods are discrete named blocks of code you can call from within a program (C# Class) - just like an RPG Subroutine; C# methods allow parameters in the call - just like RPG procedures do. Methods have lots of other features that I’ll get in to but first lets draw comparisons.
Here’s an example:
Both applications read a table called ‘People’ and print out the name of each person on the console.
They both call a subroutine/method called Get_People that takes no parameters from the main block of code.

RPG
Fpeople IF E K DISK
/FREE
exsr Get_People ;
*inlr = *on;

BegSr Get_People;
read People ;
dow not %eof ;
Dsply name ;
Read People
Enddo;
Endsr;


C#


using System;
using System.IO;
namespace ConsoleApplication1
{
class ProgramClass
{
static void Main() // Main block of code 'Main' must be in the class
{
get_People();
}
static public void get_People( )
{
using (FileStream fileStream = new FileStream(@"C:\csharp\people.txt",
FileMode.Open,
FileAccess.Read,
FileShare.None))
{
using (StreamReader streamReader = new StreamReader(fileStream))
{
string text = streamReader.ReadLine();
while (text != null)
{
Console.WriteLine(text);
text = streamReader.ReadLine();
}
}
}
Console.ReadLine(); // Pause the screen
}
}
}



As you can see, RPG is easier to read and less verbose than its C# counterpart. To be fair DB2 is part of the iSeries operating system so all the file handling is already part of the DB.

Remember these are Static methods shown in C#. A static method in C# is where there is only one instance of the method. Believe it or not you can multiple instances of a method in C#. These are called instance methods and are used more often than static methods. I'll get into the difference but the purpose of this post is to show some similarity between RPG and C# first.

Labels: , , , , , ,

1/17/08

Datasets are what?

Datasets are a layer between the actual database and your application. When you need to connect to different tables and databases, datasets can help by separating all the connecting to your different data stores and working on the actual data. The analogy with RPG is that datasets are data structures. If you read a table in an RPG program and the put that data into a data structure, updated the fields in that data structure then moved the data structure back to your table then the dataset is the data structure and the bit that moves data between the table is the data adapter.
You don't need all this of course. It's part of .NET, specifically ADO.NET - that part of the framework that's supposed to make it easier to build complex data access application. The stuff that manages and brings it in and out of your application . Kind of like the way the RPG cycle (remember that?) reads in a table automatically. You can just read and write from any database without using datasets and adapters. It's just much easier and less error prone when you use data sets and adapters to manage your data. The IDE automatically creates these when you drop a table onto a form.

When you look at the code to fill a dataset from an adapter you can see there's not much too it. The key term here is Dataset. Datasets are completely separated from the database. Think of them as a data structure where you load data from your table to. The data structure knows nothing of the table where it got the data. It's just used to hold the data in memory. All queries, updates etc. are done to the Dataset not to the data store. We let the dataadapter take care of fetching data to and from the actual table.


// build a command object and prepare an SQL statement so that you can look at your table
SqlCommand buildData = conn.CreateCommand();

cmd.CommandText = "Select * from Orders where OrdQty >100";
// Build the Data Adapater - this fills a data set
SqlDataAdapter dataAdapter = new SqlDataAdapter(buildData);

// Now create the data set. The data structure which contains the data retrieved by the data adapter
DataSet orderDataSet = new DataSet();

// Populate the dataset with the Data Adapter
dataAdapter.Fill(dataSet);

Labels: , , , , ,

1/15/08

Where to get the iSeries ADO.NET data provider

The iSeries .NET data provider is the native data provider that allows you to access iSeries data and programs using .NET in a managed way.

This is a .dll (IBM.Data.DB2.iSeries.dll ) that you add in as a reference when creating .Net apps to connect to the iSeries

Once added in you have access to all the classes and methods that simplify writing applications in .Net to leverage iSeries data in the db2 database

The dll is part of iSerices Access for windows which you can download for free (when you select the technology preview). Make sure you check 'Selective Setup' and include the Data and Programmer's toolkit so you get all the data access drivers, help and tools.


  1. Download iSeries Access from http://www-03.ibm.com/systems/i/software/access/windows/downloads.html
    Select the technology preview version. You'll have do the register rigmarole.
    If the link doesn't work, google 'iSeries Access windows' to find the latest location.

  2. Install iSeries Access making sure that you select 'custom install' to include the programmers toolkit (it comes in handy as it has examples etc.) . Once you have installed iSeries Access you will find the dll in C:\Program Files\IBM\Client Access\IBM.Data.DB2.iSeries.dll

  3. In Visual Studio, open up your project. Click on the Solution Explorer, then references. Right click references and select 'Add Reference'. A dialog box appears. Click 'Browse'. Add in the dll from the location above.

  4. Add the namespace '
    using IBM.Data.DB2.iSeries;' to your code

  5. Start using the iSeries classes! The iDB2Command is what you use to run queries, IDB2Connection to create a connection string to your iSeries db, iDB2DataAdapter gives you a cache to both connect, retrieve and update a set of data.

With the native .NET provider you have support for:

  • SQL (INSERT, UPDATE, DELETE, SELECT)
  • Stored procedure support
  • Commitment control
  • Connection pooling
  • SQL naming,Unicode, Threads and multiple databases (IASPs)

To call iSeries programs use a stored procedure.

Labels: , , , , , ,

1/13/08

Different ways to access iSeries data

Remember, you have 4 main methods to access DB2 for iSeries from .NET programs:
  1. The ADO.NET managed provider for iSeries Access for Windows, IBM.Data.DB2.iSeries. This is probably your best bet for iSeries data connectivity. Get info on it here
    and....
  2. ODBC: The Microsoft-supplied ODBC bridge provider using the iSeries Access forWindows ODBC driver for underlying database connectivity. Microsoft.Data.Odbc
  3. OLE DB: The Microsoft-supplied OLEDB bridge provider using one of the iSeries Accessfor Windows OLE DB providers for underlying database connectivity. System.Data.OleDb This is an unmanaged method.
  4. The DB2 for Linux, UNIX, and Windows (LUW) managed provider implemented by IBM software group.
Managed vs. Unmanaged

The managed provider is superior in terms of controlling actions to the DB from within your application. Managed means managed by .net - the drivers to access the iSeries are compiled into a .Net assembly. Unmanaged means that it is outside the .Net assembly - an .exe for example.
When you use OLE DB you are using an unmanaged provider so there is an extra step that has to occur from .net to the iSeries such as a bridge between the two. You should experience better performance when using the .Net managed provider.

Here's an overview of the IBM .net managed provider (from IBM)

I highly recommend reading the IBM redbook ' Integrating DB2 Universal Database for iSeries with Microsoft ADO .NET' from which the above is summarized. 'You can download it at http://www.redbooks.ibm.com/abstracts/sg246440.html

Labels: , , , ,

1/11/08

C# for iSeries RPG programmers

There are many iSeries RPG programmers out there who are keen to get started on another programming language that matches the flexibility and scope of RPG with the added web, windows and forms simplicity available in modern IDE's.
Which language will you invest your valuable time in? Java, PHP, Visual Basic, Delphi, Ruby, C#?


Java is a good, mature candidate since it also runs on the iSeries. Ruby is open and emerging as easy to learn, productive and object oriented. Delphi (Object Pascal) has been around for donkey's. PHP is mainly used for scripting and web pages so only server partial needs. Visual Basic and C# are just variations of Microsoft's powerful .NET platform but C# programmers get paid more. For someone still on the iSeries you will want a language that has excellent connectivity to the black box. That leaves Java and C#. C# has Linq! and is far easier than Java at creating windows desktop applications but Java does run on the iSeries. So it's a toss up but my friends, Linq pushes the argument to C#.

Let's look at C#.
C# (like Java) can be hard to read, is full of abstruse concepts such as polymorphism, inheritance and encapsulation. Five lines of RPG could be one line in c# and one line in RPG could be five in c#.
It's Geeky. At first glance code will appear to operate your vacum cleaner but will just read a file and print its contents. It gives you lots of ways to accomplish the same thing. Lots.
It's not simple. It's not easy. It's a pain in the ass.
It's a great language.

I recommend that RPG developers dive in to c# despite the challenges. The best way to deal with challenges is, of course, to ignore them. Yes, run away. Start writing code c# just as you would in RPG. In other words I am advocating to begin your next language which is built specifically for object oriented (OO) development to start using it as a functional procedural language. Write short little programs to display iSeries data in grids for the web, for windows, for handhelds. Think of c# as RPG for the desktop.
You may well be persecuted by OO idealogues who are (bitterly) passionate about the 'right ' way to code. They like 'coding'. RPG programmers like 'going home at 5'. They really couldn't give a shite. RPG developers are for the most part business oriented types who create software to solve real life business situations.

As time passes you'll find that you'll write more complicated code and will need to start using object oriented principles.Keep your eyes on this blog for step by step instructions for writing c# programs for use against the iSeries data and legacy applications and together we will work up to object oriented development beginning with procedural C# - let's call it RPG#.

Labels: , , , ,

1/10/08

Using .NET Linq with the DB2 - release date?

Though IBM has pledged to provide Linq to access DB2 programmatically within C# - it doesn't exist yet. In fact, Linq to SQL only works for Microsft SQL. You can do a backdoor version by using an OLEDB linked server in SQL Server for example. IBM won't tell us when Linq can access DB2 so keep an eye out at their Developer Works site at http://www-128.ibm.com/developerworks/wikis/display/DB2/DB2+and+.NET+FAQ

Labels: , , , , , ,

12/17/07

Magic Chewing Gum

OK I'm going to tell you something really cool. If nothing else this should be the reason to switch to c#... LINQ or Language Integrated query.
Technically LINQ is magic chewing gum created by Celtic druids 5,000 years ago out of the residue at the bottom of guiness barrels to bring all the warring tribes of Ireland together. Fionn McCool tried it and became king. At the annual spitting contest he spat a wad so far that it exploded through a worm hole ending up on Anders Hejlsberg's desk in Redmond as a USB stick of Juicy fruit. Once Anders plugged the magic chewing gum into his PC he was able to incorporate LINQ into .Net and this virtual gum is now able to stick together disparate pieces of data from any source whatsoever.

With LINQ C# is now a juicy data oriented language.
The problem we face today is a multitude of different types of data such as Microsoft excel spreadsheets, the e-mail messages, xml, databases, queues, registries, blah blah blah. With each of these comes their own awful object model. You have to learn all these terrible APIs and access methodologies like a dope which is another big turnoff with these multiplatform development systems like .net. With LINQ there is now a single way to access any type of data. You can query iSeries data, arrays, xml all in the same way without sacrificing what you can do with all these types of data. Another plus is that when you compile your code with LINQ statements they are checked for the correct type of field and objects. You know this in RPG when you try to compile a program without defining the field that you are using.
I know you're probably thinking that ODBC does the same thing because you can use SQL statements to access different types of databases but it doesn't check the types at compile time and it only works for relational databases. LINQ has turned c# into a real language. It makes it more of a data language. It makes it cool.

Here's a simple example:

Linq Where selection

You can only have a beer if you're over 21. The query expression creates a new sequence of numbers that satisfy the selection criteria. The for each section iterates over each element in this new sequence and prints its value.

public void AllowedToDrink() {
int[] numbers = { 25, 1, 17, 44, 20, 9, 81, 26, 37, 12, 0 };

var lowNums =
from n in numbers
where n > 20
select n;

Console.WriteLine("These People Can Have a Beer:");
foreach (var b in lowNums) {
Console.WriteLine(b);
}
}

Result

Numbers > 21 :
4
1
3
2
0

Labels: , , , , , ,