Home

Introduction to the LINQ and Class

     

Introduction

A list used in a LINQ statement can be made of any type of value (numbers, strings, etc), as long as the values are of the same type. Here is an example:

using System;
using System.Linq;

public class Exercise
{
    public static int Main()
    {
        var names = new string[5];

        names[0] = "Patricia Katts";
        names[1] = "Raymond Kouma";
        names[2] = "Hél�ne Mukoko";
        names[3] = "Paul Bertrand Yamaguchi";
        names[4] = "Gertrude Monay";

        var name = from n
                   in names
                   select n;

        foreach (var member in name)
            Console.WriteLine("Member: {0}", member.ToString());
            
        return 0;
    }
}

This would produce:

Numbers

The values used in a LINQ statement can also come from a class. For example, instead of using one of the primitive types to create a list, you can use your own class. Here is an example:

public class Employee
{
    public int EmployeeNumber;
    public string FirstName;
    public string LastName;
    public double HourlySalary;
}

You primarily use the class as you would any other. In your LINQ statement, you can refer to all members of the collection:

using System;
using System.Linq;

public class Employee
{
    public int EmployeeNumber;
    public string FirstName;
    public string LastName;
    public double HourlySalary;
}

public class Exercise
{
    public static int Main()
    {
        var empls = new Employee[5];

        empls[0] = new Employee();
        empls[0].EmployeeNumber = 971974;
        empls[0].FirstName = "Patricia";
        empls[0].LastName = "Katts";
        empls[0].HourlySalary = 24.68;

        empls[1] = new Employee();
        empls[1].EmployeeNumber = 208411;
        empls[1].FirstName = "Raymond";
        empls[1].LastName = "Kouma";
        empls[1].HourlySalary = 20.15;

        empls[2] = new Employee();
        empls[2].EmployeeNumber = 279374;
        empls[2].FirstName = "Hél�ne";
        empls[2].LastName = "Mukoko";
        empls[2].HourlySalary = 15.55;

        empls[3] = new Employee();
        empls[3].EmployeeNumber = 707912;
        empls[3].FirstName = "Bertrand";
        empls[3].LastName = "Yamaguchi";
        empls[3].HourlySalary = 24.68;

        empls[4] = new Employee();
        empls[4].EmployeeNumber = 971394;
        empls[4].FirstName = "Gertrude";
        empls[4].LastName = "Monay";
        empls[4].HourlySalary = 20.55;

        var staff = from n in empls select n;

        return 0;
    }
}

In this case, the value of the select expression represents the whole variable, which are all members of the collection. If you want to get a property (or a member) of the class, apply the period operator to the value of select and access the desired member. Here is an example:

using System;
using System.Linq;

public class Employee
{
    public int EmployeeNumber;
    public string FirstName;
    public string LastName;
    public double HourlySalary;
}

public class Exercise
{
    public static int Main()
    {
        var empls = new Employee[5];

        . . . No Change

        var lastNames = from n
                        in empls
                        select n.LastName;

        foreach (var member in lastNames)
            Console.WriteLine("Member: {0}", member.ToString());

        return 0;
    }
}

This would produce:

Numbers

This technique allows you to access only one member of the class.

As mentioned already, the select statement primarily produces the whole collection of the values of the variable. Since this value represents a collection, you can use it in a list-based such scenario. In this case, to access a member of the class, use a for or foreach loop to get each item of the collection variable and apply the period operator on that value.

Practical Learning: Creating a Query

  1. Change the Load event as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace AltairRealtors1
    {
        public class AltairRealtors
        {
            static Property[] lstProperties;
    
            public static int Main(string[] args)
            {
                FileStream stmProperties = null;
                BinaryFormatter bfmProperties = new BinaryFormatter();
    
                // This is the file that holds the list of properties
                string Filename = @"C:\Altair Realtors\Properties.atr";
    
                // Find out if there is already a file that contains a list of properties.
                // If that file exists, open it.
                if (File.Exists(Filename))
                {
                    stmProperties = new FileStream(Filename,
                                                   FileMode.Open,
                                                   FileAccess.Read,
                                                   FileShare.Read);
    
                    try
                    {
                        // Retrieve the list of items from file
                        lstProperties = (Property[])bfmProperties.Deserialize(stmProperties);
    
                        var numbers = from iNumbers
                                      in lstProperties
                                      select iNumbers.PropertyNumber;
    
                        int i = 0;
    
                        Console.WriteLine(" #  Prop #");
                        Console.WriteLine("-----------");
                        foreach (var nbr in numbers)
                        {
                            Console.WriteLine("{0,2}. {1}", (i + 1).ToString(), nbr);
                            i++;
                        }
                        Console.WriteLine("==========");
                    }
                    finally
                    {
                        stmProperties.Close();
                    }
                }
    
                return 0;
            }
        }
    }
  2. Execute the application to see the result
     
    Numbers
  3. Close the DOS window and return to your programming environment
  4. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace LINQ1
    {
        public class AltairRealtors
        {
            static Property[] lstProperties;
    
            public static int Main(string[] args)
            {
                FileStream stmProperties = null;
                BinaryFormatter bfmProperties = new BinaryFormatter();
    
                // This is the file that holds the list of properties
                string Filename = @"C:\Altair Realtors2\Properties.atr";
    
                // Find out if there is already a file that contains a list of properties.
                // If that file exists, open it.
                if (File.Exists(Filename))
                {
                    stmProperties = new FileStream(Filename,
                                                   FileMode.Open,
                                                   FileAccess.Read,
                                                   FileShare.Read);
    
                    try
                    {
                        // Retrieve the list of items from file
                        lstProperties = (Property[])bfmProperties.Deserialize(stmProperties);
    
                        var properties = from props
                                         in lstProperties
                                         select props;
    
                        int i = 1;
    
                        Console.WriteLine("+===+========+==============+===============+=======+===========+======+=======+=======+======+===========+");
                        Console.WriteLine("| # | Prop # | Type         | City          | State | Condition | Beds | Baths |Stories| Year | Value     |");
                        Console.WriteLine("+===+========+==============+===============+=======+===========+======+=======+=======+======+===========+");
                        foreach (var prop in properties)
                        {
                            Console.WriteLine("| {0,2}| {1,-6} | {2,-12} | {3,-13} |  {4,-4} | {5,-9} |  {6,-3} |  {7,-5}  |   {8,-4}| {9,-4} | {10,6} |",
                                              i, prop.PropertyNumber, prop.Type, prop.City, prop.State, prop.Condition, prop.Bedrooms,
                                              prop.Bathrooms.ToString("F"), prop.Stories, prop.YearBuilt, prop.MarketValue.ToString("F"));
                            Console.WriteLine("+---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+");
    
                            i++;
                        }
                    }
                    finally
                    {
                        stmProperties.Close();
                    }
                }
    
                return 0;
            }
        }
    }
  5. Execute the application to see the result
    +===+========+==============+===============+=======+===========+======+=======+=======+======+===========+
    | # | Prop # | Type         | City          | State | Condition | Beds | Baths |Stories| Year | Value     |
    +===+========+==============+===============+=======+===========+======+=======+=======+======+===========+
    |  1| 524880 | SingleFamily | Silver Spring |  MD   | Good      |  4   |  2.50 |   3   | 1995 | 495880.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    |  2| 688364 | SingleFamily | Alexandria    |  VA   | Excellent |  4   |  3.50 |   2   | 2000 | 620724.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    |  3| 611464 | SingleFamily | Laurel        |  MD   | Good      |  1   |  0.00 |   2   | 0    | 422625.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    |  4| 749562 | Townhouse    | Gettysburg    |  WV   | Good      |  3   |  2.50 |   3   | 2002 | 425400.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    |  5| 420115 | Unknown      | Washington    |  DC   | Unknown   |  2   |  0.00 |   0   | 1982 | 312555.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    |  6| 200417 | Condominium  | Germantown    |  MD   | Excellent |  2   |  1.00 |   0   | 0    | 215495.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    |  7| 927474 | Townhouse    | Arlington     |  VA   | BadShape  |  4   |  2.50 |   3   | 1992 | 415665.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    |  8| 682630 | SingleFamily | Martinsburg   |  WV   | Good      |  4   |  3.50 |   3   | 2005 | 325000.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    |  9| 288540 | Condominium  | Silver Spring |  MD   | Good      |  1   |  1.00 |   0   | 2000 | 242775.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 10| 247472 | SingleFamily | Silver Spring |  MD   | Excellent |  3   |  3.00 |   3   | 1996 | 625450.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 11| 297446 | Townhouse    | Laurel        |  MD   | Unknown   |  4   |  1.50 |   2   | 2002 | 412885.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 12| 924792 | SingleFamily | Washington    |  DC   | Good      |  5   |  3.50 |   3   | 2000 | 555885.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 13| 294796 | SingleFamily | Falls Church  |  VA   | Excellent |  5   |  2.50 |   2   | 1995 | 485995.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 14| 811155 | Condominium  | Alexandria    |  VA   | Good      |  1   |  1.00 |   0   | 2000 | 352775.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 15| 447597 | Townhouse    | Hyattsville   |  MD   | Excellent |  3   |  2.00 |   3   | 1992 | 365880.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 16| 297415 | Townhouse    | ashington     |  DC   | Good      |  4   |  3.50 |   1   | 2004 | 735475.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 17| 475974 | SingleFamily | Gaithersburg  |  MD   | Unknown   |  4   |  2.50 |   1   | 1965 | 615775.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 18| 927409 | Condominium  | McLean        |  VA   | Excellent |  1   |  1.00 |   12  | 2006 | 485900.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 19| 304750 | Condominium  | Washington    |  DC   | Unknown   |  2   |  2.00 |   6   | 1992 | 388665.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    | 20| 207850 | Townhouse    | Rockville     |  MD   | Good      |  3   |  2.50 |   2   | 1988 | 525995.00 |
    +---+--------+--------------+---------------+-------+-----------+------+-------+-------+------+-----------+
    Press any key to continue . . .
  6. Close the DOS window and return to your programming environment

Using a Method

To perform a more particular operation on a class, you can create a method in it and then call that method in your LINQ statement. This means that, just as you can access a field or a property of a class, you can access any of its internal or public methods. Here is an example of a method created in a class:

using System;
using System.Linq;

public class Employee
{
    public int EmployeeNumber;
    public string FirstName;
    public string LastName;
    public double HourlySalary;

    public Employee(int number = 0,
                       string firstName = "John",
                       string lastName = "Doe",
                       double salary = 0D)
    {
        EmployeeNumber = number;
        FirstName = firstName;
        LastName = lastName;
        HourlySalary = salary;
    }

    internal string GetFullName()
    {
        return LastName + ", " + FirstName;
    }
}

public class Exercise
{
    public static int Main()
    {
        var empls = new Employee[5];

        empls[0] = new Employee();
        empls[0].EmployeeNumber = 971974;
        empls[0].FirstName = "Patricia";
        empls[0].LastName = "Katts";
        empls[0].HourlySalary = 24.68;

        empls[1] = new Employee();
        empls[1].EmployeeNumber = 208411;
        empls[1].FirstName = "Raymond";
        empls[1].LastName = "Kouma";
        empls[1].HourlySalary = 20.15;

        empls[2] = new Employee();
        empls[2].EmployeeNumber = 279374;
        empls[2].FirstName = "Hél�ne";
        empls[2].LastName = "Mukoko";
        empls[2].HourlySalary = 15.55;

        empls[3] = new Employee();
        empls[3].EmployeeNumber = 707912;
        empls[3].FirstName = "Bertrand";
        empls[3].LastName = "Yamaguchi";
        empls[3].HourlySalary = 24.68;

        empls[4] = new Employee();
        empls[4].EmployeeNumber = 971394;
        empls[4].FirstName = "Gertrude";
        empls[4].LastName = "Monay";
        empls[4].HourlySalary = 20.55;

        var fullNames = from names
                        in empls
                        select names.GetFullName();

        foreach (var member in fullNames)
            Console.WriteLine("Member: {0}", member.ToString());

        Console.WriteLine();
        return 0;
    }
}

This would produce:

Numbers

Using Built-In Classes

There are two types of built-in classes you can use in your application when it comes to LINQ. You can use any of the non-generic collection classes to create a list of values. The other category is the generic collection classes.

Using a Collection-Based Variable

We mentioned that the List factor of our formula could be an array. It can also be a collection-based variable; that is, a variable created from a collection-based class. When creating a LINQ expression, the collection class you use must implement the IEnumerable generic interface. If you want, you can create your own class that implements this interface but the .NET Framework provides a complete set of classes that should suit every need. One of the built-in generic classes of the .NET Framework is called List and you can easily use it to create a list of values. Here is an example:

private void Exercise_Load(object sender, EventArgs e)
{
    var numbers = new List<double>();

    numbers.Add(12.44);
    numbers.Add(525.38);
    numbers.Add(6.28);
    numbers.Add(2448.32);
    numbers.Add(632.04);
}

After creating the collection, you can use the same LINQ formula we saw for an array. Here is an example:

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

public class Exercise
{
    public static int Main()
    {
        var numbers = new List<double>();

        numbers.Add(12.44);
        numbers.Add(525.38);
        numbers.Add(6.28);
        numbers.Add(2448.32);
        numbers.Add(632.04);

        var number = from n
                     in numbers
                     select n;

        foreach (var nbr in number)
            Console.WriteLine("Member: {0}", nbr);

        Console.WriteLine();
        return 0;
    }
}

This would produce the same result as seen earlier. Notice that, as always, the var keyword does not itself indicate the type of variable it is dealing with.

Practical Learning: Closing the Lesson

  1. Close your programming environment
  2. When asked whether you want to save, click Discard
 

Previous Copyright © 2010-2011 FunctionX Next