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.
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:
In the .NET tab of the Add Reference dialog box, you can click System.Core
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.
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:
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;
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:
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:
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:
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:
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. 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.
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||