Page 1 of 1

Using LINQ in C# Part I

#1 PsychoCoder  Icon User is offline

  • Google.Sucks.Init(true);
  • member icon

Reputation: 1641
  • View blog
  • Posts: 19,853
  • Joined: 26-July 07

Post icon  Posted 18 November 2008 - 11:11 AM

I have recently seen many requests for Language Integrated Query (LINQ) with C#, so I thought I'd take the time to write up a series of tutorials, both explaining what LINQ is, and how it works. In this first tutorial we will barely scratch the surface when it comes to the power of LINQ and it's uses. The tutorials will progress in complexity as we move from tutorial to tutorial, so for those experienced programmers bear with me. So what is LINQ, in simple terms, LINQ supports type safe data querying. LINQ is a language extension that allows this to happen. Data to use with LINQ can come from several forms:
  • XML
    • LINQ to XML

  • Database
    • LINQ-Enabled ADO.NET

    • LINQ To SQL

    • LINQ To DataSet

    • LINQ To Entities

  • Objects
    • LINQ To Objects
In this first tutorial we will be looiking at LINQ To Objects, how we can create a custom object, in our case a class, and query the data from it just as you would a database. In this first part we will also be looking at how LINQ works, new items in the .Net 3.0 Framework that makes our lives easier when it comes to using LINQ, and some new keywords introduced in 3.0, specifically for utilizing LINQ in your applications.

Let's first take a look at a very basic, simplistic LINQ query to see how it is structured
var query = from accounts in database.Accounts where
		(account.Balance < 1000) && (account.Balance > 100)
		select new { account.Name, account.Address, account.Balance };



The results of this query would consist of an account name, address, balance of all accounts with a balance between 100 and 1000 dollars in their accounts. If you look at the sample query we just looked at you will notice that the syntax is very close to that of SQL, which was the initial dream of Anders Hejleberg (Creator of C#) ad Peter Golde had for the extension of C# for better integrated data querying capabilities.

The introduction of LINQ into the C# programming world introduced two new items, Anonymous Methods and the Lambda Expression. The main difference in an Anonymous Method and a Lambda Expression is the Lambda Expression that contain expressions and statements. It can also be used to create delegates.

Let's take a quick look at how the Lambda Expression can be used to create a delegate, and much more graceful at that. First the traditional method

delegate int del(int i);
del _Delegate = x => x * x;
int j = _Delegate(5); //j = 25



Now let's see how much simpler this can be using the System.Link.Expressions Namespace

Expression<del> = x => x * x;



Lambdas are used in method based LINQ queries as arguments to a standard operator method, such as the WHERE clause. In this next example we will be introduced to the IEnumerable Interface and the IQueryable Interface. From these two we will extract methods to implement standard operators such as WHERE, SELECT, ORDER BY, and many, many more. So let's take a look at a simple example using IEnumerable

private static void UseIEnumereableToUseWhereClause()
{
    string[] names = { "Richard", "Marty", "Chris", "Josh", "Danny", "Robert" };

    IEnumerable<string> list= cities.Where(delegate(string s) { return s.StartsWith("R"); });

    // once again list will return only Richard and Robert
}



Now lets take a look at this same example, but this time we'll be using a Lambda Expression to simplify things

private static void UseIEnumereableToUseWhereClause()
{
    string[] names = { "Richard", "Marty", "Chris", "Josh", "Danny", "Robert" };

    IEnumerable<string> list= names.Where(s => s.StartsWith("R")); 

    // once again list will return only Richard and Robert
}



Now lets take a look at using LINQ to query an object, in this case a Clients class we will create. This will be a simple class consisting of 4 properties, first name, last name, client id, and referral id Here is what our class will look like

class Client
{
    private string _firstName;
    private string _lastName;
    private int _clientID;
    private int _referralID;

    public int ReferralID
    {
        get { return _referralID; }
        set { _referralID = value; }
    }

    public int ClientID
    {
        get { return _clientID; }
        set { _clientID = value; }
    }

    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    public string LastName
    {
        get { return _lastName; }
        set { _lastName = value; }
    }
}



Now we need to add some items to our Person class so we can take a look at how we can use LINQ to return data from it

var Clients = new List<Client> 
           {
             new Client { ClientID = 1, FirstName = "Joe", LastName = "Smith", ReferralID = 31 },
             new Client { ClientID = 2, FirstName = "John", LastName = "Brown", ReferralID = 15 },
             new Client { ClientID = 3, FirstName = "Richard", LastName = "Smith", ReferralID = 31 }
           };



Now we have our Client class populated with data, we will now use LINQ to query our class for all the first names of clients that have a referral id of 31

var ClientsFound = from c in Clients where c.ReferralID == 31 select c.FirstName



You will first notice that I'm using three keywords that arent available in C# 2.0, first is var. The var keyword allows us to declare new variables whose type is inferred from the expressions that initialized the variable, in our class is of type Clients. The next is the from keyword. This is also new in 3.0, it falls into the Query Keywords in the new Framework. Lastly we use another Query Keyword, select, which allows us to select only a specific group of data.

All those MSSQL users out there are now thinking that this does truly resemble Transact-SQL, and you are right.

Back on topic, we've performed the query to get the data we want, now let's print this out to the screen (in a console application for this demonstration) to see what we've got

foreach(var Item in ClientsFound)
{
     Console.WriteLine("First Name: " + Item.ToString());
}



The result of that would be

Quote

First Name: Joe
First Name: Richard


So that is how you can utilize LINQ to query your objects, just like you would a database table. I know this was a pretty high level overview of what LINQ is and how we can utilize it in our applications, but as we move on we will look deeper and deeper into this fascinating extension to the .Net Framework. Keep an eye out for Part II, and thanks for reading :)

Happy Coding!

Is This A Good Question/Topic? 0
  • +

Replies To: Using LINQ in C# Part I

#2 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2263
  • View blog
  • Posts: 9,467
  • Joined: 29-May 08

Posted 19 November 2008 - 05:00 PM

Nice Tutorial. Explains thing in a lot more detail than I did.
VB.Net + LINQ Tutorial
Was This Post Helpful? 0
  • +
  • -

#3 juanma  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 20-August 10

Posted 17 September 2010 - 06:19 AM

I think you want to say in word cities
IEnumerable<string> list= cities.Where(delegate(string s) { return s.StartsWith("R"); }); 


the word names
IEnumerable<string> list= names.Where(delegate(string s) { return s.StartsWith("R"); }); 


Nice tutorial. Thanks
Was This Post Helpful? 0
  • +
  • -

#4 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2263
  • View blog
  • Posts: 9,467
  • Joined: 29-May 08

Posted 17 September 2010 - 07:58 AM

View Postjuanma, on 17 September 2010 - 01:19 PM, said:

I think you want to say in word cities
IEnumerable<string> list= cities.Where(delegate(string s) { return s.StartsWith("R"); }); 


the word names
IEnumerable<string> list= names.Where(delegate(string s) { return s.StartsWith("R"); }); 


Nice tutorial. Thanks

PsychoCoder, is using lambda syntax, which creates an anonymous delegate.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1