News   Articles   Sources   Code libraries    RSS

Language:

English   Russia  

Current filter:

All   C#   C++   C  



Log in:

Name
Pass

Register

Michael Flenov

Linq


Language:C#
Category:Database
Date: 2008-07-04
Author:Michael Flenov
Attachment:Download

There are many new features in Visual Studio 2008 I liked. One of them is .NET Framework 3.5. In this article I will describe features I am attracted most of all.

First of all I want to thanks C# developers for var operator. You can declare implicit type variables. It’s incredible! It’s a bad programming! No. It is a good feature. .NET Framework determines a variable type itself in time of declaration. The next example shows us, how to declare an implicitly integer variable :

var intval = 1;

Do you want some more examples? I have some:

 var anumber = 10;
 var astring = "The string";
 var anarray[] = {10, 20, 30};

What will be when I declare integer variable and change the value to a string? There is will be an error. Let’s take a look on the next example:

 var anumber = 10; 
 anumber = "The string"; // Error!!!

In the first line of code I declare anumber variable. .NET interprets the variable like integer. In the second line of code I’m trying to change value to a string. It is an error!!!

Another one feature is a property declaration. Old style was looks like:

int propertyVariable;
public int PropertyName
{
 get { return propertyVariable; }
 set { propertyVariable = value; } 
}

Do you think there are a lot of code? I think – Yes. Now you can declare properties with a less bunch of code:

 public int PropertyName { get; set; }

As you see the all declaration can be placed in one line. You don’t have to declare an additional private variable. You may access to property using the property name directly.

A next one new feature of Visual Studio - LINQ. What is it? It is a new extension to the .NET Framework that encompasses language-integrated database operations like queries, sets and operations. The LINQ extends C# native language with new capabilities for queries. The LINQ can work with not only databases but XML and user defined structures. You can write queries to your data collection!

Do you want an example? I have one for you:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqTestApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            // array of numbers
            var numbers = new int[] { 1, 2, 4, 7, 9, 12 };

            // query to array of numbers
            var evenNumbers = from p in numbers
                             where (p % 2) == 0
                             select p;

            // show query result
            foreach (var val in evenNumbers)
                Console.WriteLine(val);

            // wait for the Enter
            Console.ReadLine();
        }
    }
}

Here is the query to array. The query returns even numbers (residue of division equals to 0).I don’t think about variables type in the foreach loop because I use var variable.

Let’s take a look a bit closer. First of all we declare an array of number (numbers variable). After that we use LINQ query to get needed data:

from p in numbers
where (p % 2) == 0
select p;

The LINQ queries will be easy to you if you know SQL. Our query is very similar to SQL query, but select, from and where operators go in different sequence. After FROM operator we have to place object to which we write the query. In the example above we write the query to get data from the numbers array. After WHERE operator we have to write query condition.

Another one example shows us how to write query to a List collection:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqToUserDataApplication
{
  public class User
  {
    public string UserName { get; set; }
    public string City { get; set; }
    public string Phone { get; set; }

    public override string ToString()
    {
      return UserName + "\t" + City + "\t" + Phone;
    }
  }

  class Program
  {
    static void Main(string[] args)
    {
       var users = new List
       {
        new User { UserName = "John", City = "New York", Phone = "0201513165" },
        new User { UserName = "David", City = " New York ", Phone = "74854646" },
        new User { UserName = "Serge", City = " New York ", Phone = "6786876" },
        new User { UserName = "Michael", City = "Toronto", Phone = "454849" },
        new User { UserName = "Doe", City = " Toronto", Phone = "489678" },
        new User { UserName = "Annabel", City = "Ottawa", Phone = "7897964" }
       };

       var results = from c in users
             where c.City == " Toronto"
             select c;

       foreach (var c in results)
         Console.WriteLine(c);

       Console.ReadLine();
    }
  }
}

In the example above I declare User class to store information about an user. To store users list I use List class. How can I find all users in Toronto city? I can use a loop, but we can use LINQ too. Here is a query example that returns us all users from Toronto city:

var results = from c in users
    where c.City == "Toronto"
    select c;

How it looks like? It looks cool to me :).

A next example will show us how to get data from XML file. Let us suppose we have a next XML file:

<?xml version="1.0"?>

<peoples Version="1">
  <Persen name="John" city="Toronto" phone="01" />
  <Persen name="David" city="Toronto" phone="02" />
  <Persen name="Amanda" city="Toronto" phone="03" />
  <Persen name="Michael" city="New York" phone="04" />
  <Persen name="Annabelle" city="New York" phone="05" />
  <Persen name="Ron" city="Ottawa" phone="06" />
  <Persen name="Stella" city=" Ottawa " phone="07" />
</peoples>

How we can get data from it? A first way is to load data to IEnumerable and use query to collection:

static IEnumerable GetPeoples()
{
  return from c in XDocument.Load("peoples.xml").
             Descendants("peoples").Descendants()
  select new Person 
  {
   UserName = (string)c.Attribute("name"),
   City = (string)c.Attribute("city"),
   Phone = (string)c.Attribute("phone")
  };
}

The GetPeople function returns collection of Person classes that loaded from XML file. Next code shows us how to use the function in a query :

var results = from c in GetPeoples()
where c.City == "Toronto"
select c;

A next way to get data from XML file:

Console.WriteLine("Query result for Toronto");
XDocument doc = XDocument.Load("peoples.xml");

var r = from c in doc.Descendants("peoples").Descendants()
where (string)c.Attribute("city") == "Toronto"
select c;

In this way we don't have to use an additional class like Person. We get data directly from XML file.

Let't try to change the data from XML and store it to another one file:

 XElement outXML = new XElement("PeoplesFromToronto",
  from person in r
   select new XElement("Person",
     new XAttribute("name", (string)person.Attribute("name")),
     new XElement("city", (string)person.Attribute("city")),
     new XElement("phone", (string)person.Attribute("phone"))
    ));
   outXML.Save("out.xml");

Full source code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace XMLLinq
{
 public class Person
 {
  public string UserName { get; set; }
  public string City { get; set; }
  public string Phone { get; set; }

  public override string ToString()
  {
   return UserName + "\t" + City + "\t" + Phone;
  }
 }

 class Program
 {
  static IEnumerable<Person> GetPeoples()
  {
   return from c in XDocument.Load("peoples.xml").
             Descendants("peoples").Descendants()
   select new Person 
   {
    UserName = (string)c.Attribute("name"),
    City = (string)c.Attribute("city"),
    Phone = (string)c.Attribute("phone")
   };
  }

 static void Main(string[] args)
 {
  Console.WriteLine("Query result Moscow");
  var results = from c in GetPeoples()
     where c.City == "Moscow"
     select c;

  foreach (var c in results)
    Console.WriteLine(c);

  Console.WriteLine("Query result for Piter");
  XDocument doc = XDocument.Load("peoples.xml");

  var r = from c in doc.Descendants("peoples").Descendants()
     where (string)c.Attribute("city") == "Piter"
     select c;

  foreach (var c in r)
    Console.WriteLine(c);

  XElement outXML = new XElement("PeoplesFromPiter",
     from person in r
     select new XElement("Person",
       new XAttribute("name", (string)person.Attribute("name")),
       new XElement("city", (string)person.Attribute("city")),
       new XElement("phone", (string)person.Attribute("phone"))
      ));
   outXML.Save("out.xml");

   Console.ReadLine();
  }
 }
}

There are many new features in Visual Studio 2008 I liked. One of them is .NET Framework 3.5. In this article I will describe features I am attracted most of all. Many people are still unfamiliar with this program. So, what's important here is that we have a detailed breakdown of this new created software that's been stirring a lot of people's heads. With this, anyone who has access to the Internet powered with a good broadband service shouldn't have any reason not to know a thing about .NET Framework 3.5.

Download Attachment


Comments:

: Do not use linq

Do not use linq in your projects. It is bad technology because the data access code must be separated from visualization.


Flenov : Do use Linq

You may write the Linq code to separate class files and libraries. This approach will be suitable to the Model View Technology. I do not recommend to use Linq in your project. You have to make decision yourself.


Send your comment

Your name:
Vote:
Title:
Comment:
Protection code:





Submit an article   Submit a file

Copyright © HackishCode.com 2008. All rights reserved
WEB Design and WEB Development by WEB consulting company ProfWebDev.com
www.hackishcode.com