Home

Letting New Values in LINQ

     

Letting a Local Variable

We saw that you can get the result of a LINQ statement from the select section. In reality, the select statement simply indicates that the result is ready and it hands it to the other parts of the program. Instead of getting the result directly from the select statement, you can first store it in a local LINQ variable. This allows you to treat the result as a variable that you can then manipulate before getting the final result.

To create a local variable in the LINQ statement, you can use the let operator. You must use it before the select statement to hold the result and you must initialize the variable. Normally, the variable can hold a constant value. At the end of the query, you can select that let variable and later use it as the returned 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 Label lblPrincipal;
    private TextBox txtPrincipal;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        lblPrincipal = new Label();
        lblPrincipal.Location = new System.Drawing.Point(12, 20);
        lblPrincipal.AutoSize = true;
        lblPrincipal.Text = "Principal:";
        
        txtPrincipal = new TextBox();
        txtPrincipal.Location = new System.Drawing.Point(80, 16);
        txtPrincipal.Size = new System.Drawing.Size(80, 20);
        txtPrincipal.TextAlign = HorizontalAlignment.Right;

        Controls.Add(lblPrincipal);
        Controls.Add(txtPrincipal);
        Text = "Loan Evaluation";
        Load += new EventHandler(ExerciseLoad);
        Size = new System.Drawing.Size(204, 84);
    }

    private void ExerciseLoad(object sender, EventArgs e)
    {
        var loan = new double[] { 1250d, 12.05d, 36d };

        var number = from n
                     in loan
                     let principal = 2465D
                     select principal;

        foreach (var nbr in number)
        {
            txtPrincipal.Text = nbr.ToString();
        }
    }

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

This would produce:

Letting a Local Variable

If your query is based on an array, you can assign a value of that array to the let variable. You can get the value based on the index that represents its position in the array. Here is an example:

private void ExerciseLoad(object sender, EventArgs e)
{
    var loan = new double[] { 1250d, 12.05d, 36d };

    var number = from n
                 in loan
                 let principal = loan[0]
                 select principal;

    foreach (var nbr in number)
    {
        txtPrincipal.Text = nbr.ToString();
    }
}

This would produce:

Letting a Local Variable

Instead of a constant value, you can create an expression and assign it to the let variable. The expression can be made of constant values. You can also use the members of the array by accessing each based on its index. 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 Label lblAmountPaid;
    private TextBox txtAmountPaid;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        lblAmountPaid = new Label();
        lblAmountPaid.Location = new System.Drawing.Point(12, 20);
        lblAmountPaid.AutoSize = true;
        lblAmountPaid.Text = "Amount Paid:";
        
        txtAmountPaid = new TextBox();
        txtAmountPaid.Location = new System.Drawing.Point(80, 16);
        txtAmountPaid.Size = new System.Drawing.Size(80, 20);
        txtAmountPaid.TextAlign = HorizontalAlignment.Right;

        Controls.Add(lblAmountPaid);
        Controls.Add(txtAmountPaid);
        Text = "Loan Evaluation";
        Load += new EventHandler(ExerciseLoad);
        Size = new System.Drawing.Size(204, 84);
    }

    private void ExerciseLoad(object sender, EventArgs e)
    {
        var loan = new double[] { 800, 9, 4 }; // 1250d, 12.05d, 36d };

        // Amount Paid = Principal(1 + Interest Rate * Periods)
        //             = Principal{1 + [(Interest Rate / 100) * (Periods in Months / 12)]}
        var number = from n
                     in loan
                     let amtPaid = loan[0] * (1 + (loan[1] / 100 * loan[2]/12))
                     select amtPaid;

        foreach (var nbr in number)
        {
            txtAmountPaid.Text = nbr.ToString();
        }
    }

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

This would produce:

Letting a Local Variable

You can declare more than one let variable. When you exit the statement, you can select only one of the variables and use it outside of the query. 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 Label lblInterestPaid;
    private TextBox txtInterestPaid;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        lblInterestPaid = new Label();
        lblInterestPaid.Location = new System.Drawing.Point(12, 20);
        lblInterestPaid.AutoSize = true;
        lblInterestPaid.Text = "Interest Paid:";
        
        txtInterestPaid = new TextBox();
        txtInterestPaid.Location = new System.Drawing.Point(90, 16);
        txtInterestPaid.Size = new System.Drawing.Size(60, 20);
        txtInterestPaid.TextAlign = HorizontalAlignment.Right;

        Controls.Add(lblInterestPaid);
        Controls.Add(txtInterestPaid);
        Text = "Loan Evaluation";
        Load += new EventHandler(ExerciseLoad);
        Size = new System.Drawing.Size(180, 84);
    }

    private void ExerciseLoad(object sender, EventArgs e)
    {
        var loan = new double[] { 1250d, 12.05d, 36d };

        // Future Value  = Principal(1 + Interest Rate * Periods)
        //               = Principal{1 + [(Interest Rate / 100) * (Periods in Months / 12)]}
        // Interest Paid = Future Value - Principal
        var number = from n
                     in loan
                     let futurevalue = loan[0] * (1 + (loan[1] / 100 * loan[2] / 12))
                     let interestPaid = futurevalue - loan[0]
                     select interestPaid;

        foreach (var nbr in number)
        {
            txtInterestPaid.Text = nbr.ToString("F");
        }
    }

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

This would produce:

Letting a Local Variable

You can include a where condition in your let variable if you want to check a condition. Here is an example:

private void ExerciseLoad(object sender, EventArgs e)
{
    var loan = new double[] { 1250d, 12.05d, 36d };

    var number = from n
                 in loan
                 where loan[0] > 1000
                 let futurevalue = loan[0] * (1 + (loan[1] / 100 * loan[2] / 12))
                 select futurevalue;

    foreach (var nbr in number)
    {
        txtFutureValue.Text = nbr.ToString("F");
    }
}

The where statement can be included before or after the let statement and you would get the same result:

private void ExerciseLoad(object sender, EventArgs e)
{
    var loan = new double[] { 1250d, 12.05d, 36d };

    var number = from n
                 in loan
                 let futurevalue = loan[0] * (1 + (loan[1] / 100 * loan[2] / 12))
                 where loan[0] > 1000
                 select futurevalue;

    foreach (var nbr in number)
    {
        txtFutureValue.Text = nbr.ToString("F");
    }
}
 
 
 

Declaring New local Variables

We mentioned that we could declare one or more let variables in your query but you could get only one of those variables out of the query. To let you get more that one variable outside of the query, the LINQ provides an operator name new. It must follow the select keyword in the following formula:

var SubListName = from ValueHolder
		  in List
		  select new
		  {
		  };

As you can see, to use the new operator, after the select keyword, type new followed by an opening and a closing curly brackets, "{" and "}" . Inside the brackets, declare any variable of your choice and assign it the value you want. The value can be any constant you want. Here is an example:

private void ExerciseLoad(object sender, EventArgs e)
{
    var numbers = new double[] { 1250d, 12.05d, 36d };

    var number = from n
                 in numbers
                 select new
                 {
                     something = 6500
                 };
}

If you declare more than one variable, separate them with commas. Here are examples:

private void ExerciseLoad(object sender, EventArgs e)
{
    var numbers = new double[] { 1250d, 12.05d, 36d };

    var number = from n
                 in numbers
                 select new
                 {
                     something = 6500, another 4.006, more 5
                 };
}

Remember that you can declare each variable on its own line to make the code easier to read.

If you are using the values from an array, you can locate a value by its index and assign it to the desired local variable. Here are examples:

var number = from n
             in numbers
             select new
             {
                 Principal    = numbers[0],
                 InterestRate = numbers[1],
                 Periods      = numbers[2]
             };

Either way, to accessing a new variable outside the query, use a foreach loop to get a contextual variable. In the body of foreach, access each new variable using the period operator applied. Here are examples:

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

public class Exercise : Form
{
    private Label lblPrincipal;
    private TextBox txtPrincipal;
    private Label lblInterestRate;
    private TextBox txtInterestRate;
    private Label lblPercentSign;
    private Label lblPeriods;
    private TextBox txtPeriods;
    private Label lblMonths;
    private Label lblInterestPaid;
    private TextBox txtInterestPaid;
    private TextBox txtFutureValue;
    private Label lblFutureValue;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        lblPrincipal = new Label();
        lblPrincipal.AutoSize = true;
        lblPrincipal.Text = "Principal:";
        lblPrincipal.Size = new System.Drawing.Size(50, 13);
        lblPrincipal.Location = new System.Drawing.Point(12, 20);

        txtPrincipal = new TextBox();
        txtPrincipal.TextAlign = HorizontalAlignment.Right;
        txtPrincipal.Size = new System.Drawing.Size(81, 20);
        txtPrincipal.Location = new System.Drawing.Point(89, 17);

        lblInterestRate = new Label();
        lblInterestRate.AutoSize = true;
        lblInterestRate.Text = "Interest Rate:";
        lblInterestRate.Size = new System.Drawing.Size(71, 13);
        lblInterestRate.Location = new System.Drawing.Point(12, 51);

        txtInterestRate = new TextBox();
        txtInterestRate.Size = new System.Drawing.Size(58, 20);
        txtInterestRate.Location = new System.Drawing.Point(89, 48);
        txtInterestRate.TextAlign = HorizontalAlignment.Right;

        lblPercentSign = new Label();
        lblPercentSign.Text = "%";
        lblPercentSign.AutoSize = true;
        lblPercentSign.Size = new System.Drawing.Size(15, 13);
        lblPercentSign.Location = new System.Drawing.Point(153, 51);

        lblPeriods = new Label();
        lblPeriods.AutoSize = true;
        lblPeriods.Text = "Periods:";
        lblPeriods.Size = new System.Drawing.Size(45, 13);
        lblPeriods.Location = new System.Drawing.Point(12, 81);
            
        txtPeriods = new TextBox();
        txtPeriods.TextAlign = HorizontalAlignment.Right;
        txtPeriods.Size = new System.Drawing.Size(58, 20);
        txtPeriods.Location = new System.Drawing.Point(89, 78);

        lblMonths = new Label();
        lblMonths.Text = "Months";
        lblMonths.AutoSize = true;
        lblMonths.Size = new System.Drawing.Size(42, 13);
        lblMonths.Location = new System.Drawing.Point(153, 81);
        
        lblInterestPaid = new Label();
        lblInterestPaid.AutoSize = true;
        lblInterestPaid.Text = "Interest Paid:";
        lblInterestPaid.Size = new System.Drawing.Size(69, 13);
        lblInterestPaid.Location = new System.Drawing.Point(12, 111);

        txtInterestPaid = new TextBox();
        txtInterestPaid.TextAlign = HorizontalAlignment.Right;
        txtInterestPaid.Size = new System.Drawing.Size(81, 20);
        txtInterestPaid.Location = new System.Drawing.Point(89, 108);
        
        lblFutureValue = new System.Windows.Forms.Label();
        lblFutureValue.AutoSize = true;
        lblFutureValue.Text = "Future Value:";
        lblFutureValue.Size = new System.Drawing.Size(70, 13);
        lblFutureValue.Location = new System.Drawing.Point(12, 140);
        
        txtFutureValue = new TextBox();
        txtFutureValue.TextAlign = HorizontalAlignment.Right;
        txtFutureValue.Size = new System.Drawing.Size(81, 20);
        txtFutureValue.Location = new System.Drawing.Point(89, 137);
         
        ClientSize = new System.Drawing.Size(204, 174);
        Controls.Add(lblPrincipal);
        Controls.Add(txtPrincipal);
        Controls.Add(lblInterestRate);
        Controls.Add(txtInterestRate);
        Controls.Add(lblPercentSign);
        Controls.Add(lblPeriods);
        Controls.Add(txtPeriods);
        Controls.Add(lblMonths);
        Controls.Add(lblInterestPaid);
        Controls.Add(txtInterestPaid);
        Controls.Add(lblFutureValue);
        Controls.Add(txtFutureValue);
        MaximizeBox = false;
        MinimizeBox = false;

        StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        Text = "Loan Evaluation";
        Load += new System.EventHandler(this.ExerciseLoad);
    }

    private void ExerciseLoad(object sender, EventArgs e)
    {
        var numbers = new double[] { 6500d, 11.65d, 48u };

        var number = from n
                     in numbers
                     select new
                     {
                         Principal    = numbers[0],
                         InterestRate = numbers[1],
                         Periods      = numbers[2]
                     };

        foreach (var member in number)
        {
            txtPrincipal.Text = member.Principal.ToString();
            txtInterestRate.Text = member.InterestRate.ToString();
            txtPeriods.Text = member.Periods.ToString();
        }
    }

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

Instead of a constant or a member of an array, a new variable can be assigned an expression. The expression can be made of constants, the members of an array, or a combination of constants and members of the array. Here are examples:

private void ExerciseLoad(object sender, EventArgs e)
{
    var numbers = new double[] { 6500d, 11.65d, 48u };

    var number = from n
                 in numbers
                 select new
                 {
                     Principal    = numbers[0],
                     InterestRate = numbers[1],
                     Periods      = numbers[2],
                     Futurevalue  = numbers[0] * (1 + (numbers[1] / 100 * numbers[2] / 12)),
                     InterestPaid = (numbers[0] * (1 + (numbers[1] / 100 * numbers[2] / 12))) - numbers[0],
                 };

    foreach (var member in number)
    {
        txtPrincipal.Text = member.Principal.ToString();
        txtInterestRate.Text = member.InterestRate.ToString();
        txtPeriods.Text = member.Periods.ToString();
        txtFutureValue.Text = member.Futurevalue.ToString("F");
        txtInterestPaid.Text = member.InterestPaid.ToString("F");
    }
}

This would produce:

New Local Variables

If necessary, you can include a where statement to check a condition. The where statement must be written before the select new section. Here is ab example:

private void ExerciseLoad(object sender, EventArgs e)
{
    var numbers = new double[] { 6500d, 11.65d, 48u };

    var number = from n
                 in numbers
		 where numbers[0] > 5000
                 select new
                 {
                     Principal    = numbers[0],
                     InterestRate = numbers[1],
                     Periods      = numbers[2],
                     Futurevalue  = numbers[0] * (1 + (numbers[1] / 100 * numbers[2] / 12)),
                     InterestPaid = (numbers[0] * (1 + (numbers[1] / 100 * numbers[2] / 12))) - numbers[0]
                 };

    foreach (var member in number)
    {
        txtPrincipal.Text = member.Principal.ToString();
        txtInterestRate.Text = member.InterestRate.ToString();
        txtPeriods.Text = member.Periods.ToString();
        txtFutureValue.Text = member.Futurevalue.ToString("F");
        txtInterestPaid.Text = member.InterestPaid.ToString("F");
    }
}
 
 
   
 

Previous Copyright © 2008-2014, FunctionX Next