Home

Introduction to the LINQ

   

The Language Integrated Query

 

Introduction to Querying

When using for or foreach loops on a list, you get the value or a range of values inside of the loop. Once you exit the loop, the operation ends and you cannot access the value(s) that was(were) isolated. If you want to get the isolated value or a list of values again, you would have to perform the operation (create the loop), again. In some cases, you may want to prepare and get one value, a few values, or a range of values for later use, or to use over and over again.

To do this, you would create a value or a list of values and store that list in a variable, outside of any loop, then use the value or the list of values when needed. As applied to the for or the foreach loop, to perform this operation, you use a conditional statement that would examine the list, look for the value(s), get that value or those values that respond(s) to the condition. Any value(s) that respond(s) to the condition is(are) then stored in the new list. This technique of examining a list is referred to as querying.

Practical Learning: Introducing LINQ

  1. Start Microsoft Visual Studio and create a Windows Forms Application named AltairRealtors1
  2. To create a new class, in the Class View, right-click AltairRealtors1 -> Add -> Class...
  3. Change the name to Property and press Enter
  4. Complete the class as follows:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace AltairRealtors1
    {
        public enum PropertyType
        {
            Condominium,
            Townhouse,
            SingleFamily,
            Unknown
        }
    
        public enum PropertyCondition
        {
            Unknown,
            Excellent,
            Good,
            NeedsRepair,
            BadShape
        }
    
        [Serializable]
        public class Property
        {
            private int nbr;
            private PropertyType tp;
            private string ct;
            private string stt;
            private PropertyCondition cond;
            private short beds;
            private float baths;
            private int levels;
            private int yr;
            private decimal val;
    
            public Property()
            {
                nbr = 0;
                tp = PropertyType.Unknown;
                ct = "Unknown";
                stt = "AA";
                cond = PropertyCondition.Unknown;
                beds = 0;
                baths = 0.00F;
                levels = 0;
                yr = 1900;
                val = 0M;
            }
    
            public Property(int propNbr, PropertyType type, string city,
                            string state, PropertyCondition condition,
                            short bedrooms, float bathrooms, int stories,
                            int year, decimal value)
            {
                nbr = propNbr;
                tp = type;
                ct = city;
                stt = state;
                cond = condition;
                beds = bedrooms;
                baths = bathrooms;
                levels = stories;
                yr = year;
                val = value;
            }
    
            public int PropertyNumber
            {
                get { return nbr; }
                set { nbr = value; }
            }
    
            public PropertyType Type
            {
                get { return tp; }
                set { tp = value; }
            }
    
            public string City
            {
                get { return ct; }
                set { ct = value; }
            }
    
            public string State
            {
                get { return stt; }
                set { stt = value; }
            }
    
            public PropertyCondition Condition
            {
                get { return cond; }
                set { cond = value; }
            }
    
            public short Bedrooms
            {
                get
                {
                    if (beds <= 1)
                        return 1;
                    else
                        return beds;
                }
                set { beds = value; }
            }
    
            public float Bathrooms
            {
                get { return (baths <= 0) ? 0.00f : baths; }
                set { baths = value; }
            }
    
            public int Stories
            {
                get { return levels; }
                set { levels = value; }
            }
    
            public int YearBuilt
            {
                get { return yr; }
                set { yr = value; }
            }
    
            public decimal MarketValue
            {
                get { return (val <= 0) ? 0.00M : val; }
                set { val = value; }
            }
        }
    }
  5. In the Solution Explorer, right-click Form1.cs and click Rename
  6. Type AltairRealtors.cs and press Enter twice to display the form
  7. Design the form as follows:
     
    Altair Realtors
     
    Control Text Name Other Properties
    ListView List View   lvwProperties Anchor: Top, Bottom, Left, Right
    Columns  
    (Name) Text TextAlign Width
    colIndex #   40
    colPropertyNumber Prop #   55
    colDateListed Date Listed Center  
    colPropertyType Prop Type   85
    colCity City    
    colState State    
    colCondition Condition    
    colBedrooms Beds Right 65
    colBathrooms Baths Right 65
    colStories Stories Right 75
    colYearBuilt Year Right 70
    colMarketValue Value Right  
    Button Button Close btnClose Anchor: Bottom, Right
  8. Double-click an unoccupied area of the form and implement the Load event as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace AltairRealtors1
    {
        public partial class AltairRealtors : Form
        {
            public AltairRealtors()
            {
                InitializeComponent();
            }
    
            private void AltairRealtors_Load(object sender, EventArgs e)
            {
                Property[] lstProperties = new Property[]
                {
                    new Property(524880, PropertyType.SingleFamily, "Silver Spring", "MD",
                            PropertyCondition.Good, 4, 2.50f, 3, 1995, 495880.00M),
                    new Property(688364, PropertyType.SingleFamily, "Alexandria", "VA",
                            PropertyCondition.Excellent, 4, 3.5f, 2, 2000, 620724.00M),
                    new Property(611464, PropertyType.SingleFamily, "Laurel", "MD",
                            PropertyCondition.Good, 0, 0F, 2, 0, 422625.00M),
                    new Property(749562, PropertyType.Townhouse, "Gettysburg", "WV",
                            PropertyCondition.Good, 3, 2.5F, 3, 2002, 425400.00M),
                    new Property(420115, PropertyType.Unknown, "Washington", "DC",
                            PropertyCondition.Unknown, 2, 0F, 0, 1982, 312555.00M),
                    new Property(200417, PropertyType.Condominium, "Germantown", "MD",
                            PropertyCondition.Excellent, 2, 1f, 0, 0, 215495.00M),
                    new Property(927474, PropertyType.Townhouse, "Arlington", "VA",
                            PropertyCondition.BadShape, 4, 2.5f, 3, 1992, 415665.00M),
                    new Property(682630, PropertyType.SingleFamily, "Martinsburg", "WV",
                            PropertyCondition.Good, 4, 3.5f, 3, 2005, 325000.00M),
                    new Property(288540, PropertyType.Condominium, "Silver Spring", "MD",
                            PropertyCondition.Good, 1, 1f, 0, 2000, 242775.00M),
                    new Property(247472, PropertyType.SingleFamily, "Silver Spring", "MD",
                            PropertyCondition.Excellent, 3, 3f, 3, 1996, 625450.00M),
                    new Property(297446, PropertyType.Townhouse, "Laurel", "MD",
                            PropertyCondition.Unknown, 4, 1.5F, 2, 2002, 412885.00M),
                    new Property(924792, PropertyType.SingleFamily, "Washington", "DC",
                            PropertyCondition.Good, 5, 3.5F, 3, 2000, 555885.00M),
                    new Property(294796, PropertyType.SingleFamily, "Falls Church", "VA",
                            PropertyCondition.Excellent, 5, 2.5f, 2, 1995, 485995.00M),
                    new Property(811155, PropertyType.Condominium, "Alexandria", "VA",
                            PropertyCondition.Good, 1, 1.0F, 0, 2000, 352775.00M),
                    new Property(447597, PropertyType.Townhouse, "Hyattsville", "MD",
                            PropertyCondition.Excellent, 3, 2f, 3, 1992, 365880.00M),
                    new Property(297415, PropertyType.Townhouse, "ashington", "DC",
                            PropertyCondition.Good, 4, 3.5f, 1, 2004, 735475.00M),
                    new Property(475974, PropertyType.SingleFamily, "Gaithersburg", "MD",
                            PropertyCondition.Unknown, 4, 2.5f, 1, 1965, 615775.00M),
                    new Property(927409, PropertyType.Condominium, "McLean", "VA",
                            PropertyCondition.Excellent, 1, 1f, 12, 2006, 485900.00M),
                    new Property(304750, PropertyType.Condominium, "Washington", "DC",
                            PropertyCondition.Unknown, 2, 2f, 6, 1992, 388665.00M),
                    new Property(207850, PropertyType.Townhouse, "Rockville", "MD",
                            PropertyCondition.Good, 3, 2.5F, 2, 1988, 525995.00M)
                };
    
                FileStream stmProperties = null;
                BinaryFormatter bfmProperties = new BinaryFormatter();
    
                // If this directory doesn't exist, create it
                Directory.CreateDirectory(@"C:\Altair Realtors");
                // 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 to get it ready for the new properties.
                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);
                    }
                    finally
                    {
                        stmProperties.Close();
                    }
                }
    
                // Save the list of properties
                stmProperties = new FileStream(Filename,
                                              FileMode.Create,
                                              FileAccess.Write,
                                              FileShare.Write);
    
                try
                {
                    bfmProperties.Serialize(stmProperties, lstProperties);
                }
                finally
                {
                    stmProperties.Close();
                }
            }
        }
    }
  9. Return to the form and double-click the Close button
  10. Change the file as follows:
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    namespace AltairRealtors1
    {
        public partial class AltairRealtors : Form
        {
            Property[] lstProperties;
    
            public AltairRealtors()
            {
                InitializeComponent();
            }
    
            private void AltairRealtors_Load(object sender, EventArgs e)
            {
                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);
                    }
                    finally
                    {
                        stmProperties.Close();
                    }
                }
            }
    
            private void btnClose_Click(object sender, EventArgs e)
            {
                Close();
            }
        }
    }

Introduction to LINQ

To support the ability to query a list, you can use the Language Integrated Query, abbreviated LINQ. To use LINQ in your application, you must include the System.Core.dll assembly in your program. If you started your application as an empty project:

  • On the main menu, you can click Project -> Add Reference...
  • In the Solution Explorer, you can right-click the name of the project and click Add Reference...
  • In the Class View, you can right-click the name of the project and click Add Reference...

In the .NET tab of the Add Reference dialog box, you can click System.Core

Add Reference

Then click OK. You must then use the System.Linq namespace in your code or you can include the using System.Linq; line in your list of namespaces.

If you create an application by selecting the Windows Forms Application option from the New Project dialog box, the studio would add the necessary assemblies to your project and the necessary namespaces to your code file.

Creating a Query

To query a list, you write a statement using words and operators of the LINQ. The most fundamental operation you can perform on LINQ consists of creating, also referred to as selecting, or querying, a list of values, from an existing list such as an array. The basic formula to use is:

var SubListName = from ValueHolder in List select ValueHolder;

The var keyword, the assignment operator "=", the from keyword, the in keyword, the select keyword, and the semicolon are required.

The SubListName is a name of a new variable that will hold the list of values produced by this operation.

The ValueHolder is the name of a variable that will be used to identify each resulting member of this operation. This variable will be equivalent to getting each member of the list and that responds to a condition.

The List factor represents the name of the variable that you would have created already. The List can be an array. Here is an example:

using System;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

public class Exercise : Form
{
    private ListBox lbxNumbers;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        lbxNumbers = new ListBox();
        lbxNumbers.Location = new System.Drawing.Point(12, 12);
        lbxNumbers.Width = 100;

        Text = "Numbers";
        MinimizeBox = false;
        MaximizeBox = false;
        Controls.Add(this.lbxNumbers);
        Load += new EventHandler(ExerciseLoad);
        Size = new System.Drawing.Size(130, 145);
        StartPosition = FormStartPosition.CenterScreen;
    }

    private void ExerciseLoad(object sender, EventArgs e)
    {
        var numbers = new double[] { 12.44, 525.38, 6.28, 2448.32, 632.04 };

        var number = from n in numbers select n;

        foreach (var member in number)
            lbxNumbers.Items.Add(member.ToString());
    }

    [STAThread]
    public static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

Numbers

To make the code easier to read, you can spread the select statement to various lines. Here is an example:

var number = from n
	     in numbers
	     select n;

Introduction to LINQ and Classes

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:

private void btnShow_Click(object sender, EventArgs e)
{
    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)
        lbxEmployees.Items.Add(member.ToString());
}

This would produce:

Names

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 a 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.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnShow_Click(object sender, EventArgs e)
        {            
            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;
        }
    }
}

In this case, the value of the select expression (n) represents the whole variable, that is, 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.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            var empls = new Employee[5];

            . . . No Change

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

            foreach (var member in lastNames)
                lbxEmployees.Items.Add(member);
        }
    }
}

This would produce:

Employees

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, such as displaying the result in a list view. 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. Here is an example:

using System;
using System.Linq;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

public class Exercise : Form
{
    private Button btnShow;

    private ColumnHeader colShelfNumber;
    private ColumnHeader colVideoTitle;
    private ColumnHeader colRating;
    private ColumnHeader colYearReleased;
    private ColumnHeader colWideScreen;

    ListView lvwCollection;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        btnShow = new Button();
        btnShow.Location = new System.Drawing.Point(12, 8);
        btnShow.Width = 75;
        btnShow.Text = "Show";
        btnShow.Click += new System.EventHandler(this.btnShow_Click);

        lvwCollection = new ListView();
        lvwCollection.Anchor = AnchorStyles.Left | AnchorStyles.Top |
                               AnchorStyles.Right | AnchorStyles.Bottom;
        lvwCollection.FullRowSelect = true;
        lvwCollection.GridLines = true;
        lvwCollection.Location = new Point(12, 40);
        lvwCollection.Size = new System.Drawing.Size(395, 102);
        lvwCollection.View = View.Details;

        colShelfNumber = new ColumnHeader();
        colShelfNumber.Text = "Shelf #";
        colShelfNumber.Width = 50;
        lvwCollection.Columns.Add(colShelfNumber);

        colVideoTitle = new ColumnHeader();
        colVideoTitle.Text = "Video Title";
        colVideoTitle.Width = 160;
        lvwCollection.Columns.Add(colVideoTitle);

        colRating = new ColumnHeader();
        colRating.Text = "Rating";
        colRating.Width = 50;
        colRating.TextAlign = HorizontalAlignment.Center;
        lvwCollection.Columns.Add(colRating);

        colYearReleased = new ColumnHeader();
        colYearReleased.Text = "(c) Year";
        colYearReleased.Width = 50;
        colYearReleased.TextAlign = HorizontalAlignment.Right;
        lvwCollection.Columns.Add(colYearReleased);

        colWideScreen = new ColumnHeader();
        colWideScreen.Text = "Wide Screen?";
        colWideScreen.Width = 80;
        colWideScreen.TextAlign = HorizontalAlignment.Center;
        lvwCollection.Columns.Add(colWideScreen);

        Size = new System.Drawing.Size(425, 180);
        Controls.Add(this.btnShow);
        Controls.Add(this.lvwCollection);
        Text = "Entertainment";
    }

    private void btnShow_Click(object sender, EventArgs e)
    {
        Video[] lstVideos = new Video[]
        {
            new Video("792075", "Two for the Money", "R", "2008", true),
            new Video("900245", "Her Alibi", "PG-13", "1998", false),
            new Video("773022", "Distinguished Gentleman (The)", "R", "", false),
            new Video("", "Memoirs of a Geisha", "PG-13", "2006", true),
            new Video("961973", "Wall Street", "R", "2000", false)
        };

        var vdos = from videos
                   in lstVideos
                   select videos;

        foreach (var item in vdos)
        {
            ListViewItem lviCollection = new ListViewItem(item.ShelfNumber);

            lviCollection.SubItems.Add(item.VideoTitle);
            lviCollection.SubItems.Add(item.Rating);
            lviCollection.SubItems.Add(item.YearReleased);
            lviCollection.SubItems.Add(item.WideScreen.ToString());
            lvwCollection.Items.Add(lviCollection);
        }
    }

    [STAThread]
    public static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

public class Video
{
    public string ShelfNumber { get; set; }
    public string VideoTitle { get; set; }
    public string Rating { get; set; }
    public string YearReleased { get; set; }
    public bool WideScreen { get; set; }

    public Video(string number = "", 
                 string title = "",
                 string ratings = "",
                 string year = "",
                 bool ws = false)
    {
        ShelfNumber = number;
        VideoTitle = title;
        Rating = ratings;
        YearReleased = year;
        WideScreen = ws;
    }
}

This would produce:

Employees

Practical Learning: Creating a Query

  1. Change the Load event as follows:
    private void AltairRealtors_Load(object sender, EventArgs e)
    {
                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;
    
                        foreach (var nbr in numbers)
                        {
                            ListViewItem lviProperty = new ListViewItem((i + 1).ToString());
                            
                            lviProperty.SubItems.Add(nbr.ToString());
                            lvwProperties.Items.Add(lviProperty);
    
                            i++;
                        }
                    }
                    finally
                    {
                        stmProperties.Close();
                    }
                }
    }
  2. Execute the application to see the result
     
    Altair Realtors
  3. Return to the form and change the Load event as follows:
    private void AltairRealtors_Load(object sender, EventArgs e)
    {
                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 properties = from props
                                         in lstProperties
                                         select props;
    
                        int i = 0;
    
                        foreach (var prop in properties)
                        {
                            ListViewItem lviProperty = new ListViewItem((i + 1).ToString());
                            
                            lviProperty.SubItems.Add(prop.PropertyNumber.ToString());
                            lviProperty.SubItems.Add(prop.Type.ToString());
                            lviProperty.SubItems.Add(prop.City);
                            lviProperty.SubItems.Add(prop.State);
                            lviProperty.SubItems.Add(prop.Condition.ToString());
                            lviProperty.SubItems.Add(prop.Bedrooms.ToString());
                            lviProperty.SubItems.Add(prop.Bathrooms.ToString("F"));
                            lviProperty.SubItems.Add(prop.Stories.ToString());
                            lviProperty.SubItems.Add(prop.YearBuilt.ToString());
                            lviProperty.SubItems.Add(prop.MarketValue.ToString("F"));
                            lvwProperties.Items.Add(lviProperty);
    
                            i++;
                        }
                    }
                    finally
                    {
                        stmProperties.Close();
                    }
                }
    }
  4. Execute the application to see the result
     
    Altair Realtors
  5. Close the form 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:

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

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

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

You can then call the method:

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

foreach (var member in fullNames)
    lbxEmployees.Items.Add(member);
 

This would produce:

Employees

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.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Fundamentals
{
    public partial class Exercise : Form
    {
        public Exercise()
        {
            InitializeComponent();
        }

        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);

            var number = from n
                         in numbers
                         select n;

            foreach (var member in number)
                lbxNumbers.Items.Add(member.ToString());
        }
    }
}

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

 

Home Copyright © 2010-2014, FunctionX Next