Built-In Classes/Structures and LINQ
Built-In Classes/Structures and LINQ
Introduction to Built-In Objects
Overview
We already know that you can create a class to use in the LINQ. In reality, the .NET Framework provides a large collection of classes and structures, referred to as built-in classes. Normally, you can use most of those classes in LINQ, depending on the operation you are trying to perform. As you may know already, the most fundamental class in the .NET Framework is called object. That class is mostly used as the parent of all classes.
A LINQ With Character
As you may know already, a character is any symbol, readable or not, that can be identified. To support characters, the .NET Framework provides a structure named Char. It is represented in the C# language by the char data type. In a LINQ-based application, you can create an array of characters and use it in a select statement, as done with primitive types. Here is an example:
char[] email = new char[] { 'E', 'm', 'a', 'i', 'l', 'A', 'd', 'd', 'r', 'e', 's', 's', '@', 'Y', 'a', 'h', 'o', 'o', '.', 'C', 'o', 'm' }; var result = from address in email select address; Console.Write("Email Address: "); foreach(var c in result) { Console.Write("{0}", c); }
This would produce:
Email Address: EmailAddress@Yahoo.Com Press any key to close this window . . .
To let you perform some operations on characters, the Char structure is equipped with various properties and methods. You can access those properties or call the methods in your code. Some of the methods are static, which means you must access them from the Char structure. Here is an example:
char[] email = new char[] { 'E', 'm', 'a', 'i', 'l', '-',
'A', 'd', 'd', 'r', 'e', 's', 's',
'@', 'Y', 'a', 'h', 'o', 'o', '.', 'C', 'o', 'm' };
var result = from address
in email
select address;
Console.Write("Email Address: ");
foreach(var c in result)
{
Console.Write("{0}", char.ToLower(c));
}
This would produce:
Email Address: email-address@yahoo.com Press any key to close this window . . .
Introduction to the String Class
Overview
Probably the most used class in a regular application is named String. It is represented in C# as the string data type. The String implements many useful interfaces that allow you may comparisons between strings and conversions among types. This makes the String class a very valuable candidate for LINQ operations.
Selecting From an array of Strings
As done with primitive types so far, before using string in a LINQ statement, you can start by creating an array of strings. You can then create a regular select statement. Here is an example:
string[] movies = new string[] { "Two for the Money", "Her Alibi", "Distinguished Gentleman (The)", "Memoirs of a Geisha", "Wall Street" }; var movie = from n in movies select n; foreach (var title in movie) Console.WriteLine(title); Console.WriteLine("=======================================");
This would produce:
Two for the Money Her Alibi Distinguished Gentleman (The) Memoirs of a Geisha Wall Street ======================================= Press any key to close this window . . .
Converting a Value to String
In some applications, you deal with a value that is not a string but the section of code, such as a control, expects a string. To assist you in converting a value to a string, the String class is equipped with the overloaded ToString() method. Here is an example that calls it:s
namespace MovieCollection { public partial class Exercise : Form { public Exercise() { InitializeComponent(); } private void Exercise_Load(object sender, EventArgs e) { var movies = new string[] { "Two for the Money", "Her Alibi", "Distinguished Gentleman (The)", "Memoirs of a Geisha", "Wall Street" }; var movie = from n in movies select n; foreach (var title in movie) lbxMovies.Items.Add(title.ToString()); } } }
This would produce:
In reality, the String.ToString() method allows you to format a result to display anywhere appropriate way you want.
Selecting Some Concatenated Strings
Concatenating some strings consists of adding one to another. One way to perform this operation in a query is to add a string to each member of the result of a query. To assiste you in adding one string to another, the String class provides various options.
The String class is equipped with the Concat() method that is overloaded with 10 versions. You can use any of those versions to add strings. Here is an example:
using System.Text;
namespace Exercises
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}
private void Exercise_Load(object sender, EventArgs e)
{
string strCompany = "functionsharp.com";
string[] userNames = new[] { "cwatts", "wswanson", "jbaker", "pstones", "msanderson" };
var addresses = from un
in userNames
select string.Concat(un, "@", strCompany);
StringBuilder sbEmailAddresses = new();
foreach (string person in addresses)
{
sbEmailAddresses.Append(person);
sbEmailAddresses.Append(Environment.NewLine);
}
rtbEmailAddresses.Text = sbEmailAddresses.ToString();
}
}
}
This would produce:
Alternatively, you can use the + operator that is overloaded in the String class. Here is an example:
using System.Text;
namespace Exercises
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}
private void Exercise_Load(object sender, EventArgs e)
{
string strCompany = "functionsharp.com";
string[] userNames = new[] { "cwatts", "wswanson", "jbaker", "pstones", "msanderson" };
var addresses = from un
in userNames
select un + "@" + strCompany;
StringBuilder sbEmailAddresses = new();
foreach (string person in addresses)
{
sbEmailAddresses.Append(person);
sbEmailAddresses.Append(Environment.NewLine);
}
rtbEmailAddresses.Text = sbEmailAddresses.ToString();
}
}
}
Formatting a String
Formatting a string consists of uniting different types of values in a string and arranging the result as you see fit. To support this operation, the String class is equipped with the Format() method. You can call this method in the select clause of your LINQ statement. Here is an example:
namespace Numerotation
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}
private void Exercise_Load(object sender, EventArgs e)
{
float[] times = new[] { 8.0f, 9.5f, 7.50f, 8.5f, 6.00f, 10.5f, 8.50f };
var week = from result
in times
select string.Format("Time Worked: {0, 10:N}", result);
foreach (var item in week)
{
lbxDaysWork.Items.Add(item);
}
}
}
}
This would produce:
Support for Conditional Statements in Strings
Introduction
We already know that the LINQ supports conditional statements. In turn, the String class is equipped with methods that are used to check conditions. You can combine these aspects to create LINQ statements that check conditions on strings.
Checking for String Equality
Like all classes of the .NET Framework, the String class inherits the Equals() method of the Object class. This makes it possible to compare two strings for equality. Besides the Equals() method, the == operator is overloaded in the String class and has the same effect. Here is an example of using it:
namespace Numerotation
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}
private void btnShow_Click(object sender, EventArgs e)
{
var names = new[]
{
"Hermine", "Patrick", "Hank", "Bertine",
"Julius", "Thomas", "Jeannette", "Patrick",
"Patrick", "Raul", "David", "Paulette"
};
var name = from n
in names
where n == "Patrick"
select n;
foreach (var member in name)
lbxNames.Items.Add(member);
}
}
}
This would produce:
On the other hand, to find out if two strings are not equal, you can use the != operator.
Checking the Starting Sub-String
The String class is equipped with various types of methods to work on sub-strings. To get a list of strings that start with a certain letter or a sub-string, you can call the StartsWith() method. This is a Boolean method that is overloaded with three versions. One of the versions takes one argument that is the sub-string to find at the beginning of the string that calls it. Here is an example:
namespace Numerotation
{
public partial class Exercise : Form
{
public Exercise()
{
InitializeComponent();
}
private void Exercise_Load(object sender, EventArgs e)
{
var people = new[] {
"Hermine", "Patrick", "Hank", "Bertine",
"Julius", "Thomas", "Jeannette", "Patricia",
"Henriette", "Raul", "David", "Paulette"
};
var names = from n
in people
where n.StartsWith("P")
select n;
foreach (var member in names)
lbxNames.Items.Add(member);
}
}
}
This would produce:
The String.StartsWith() method returns true if the variable that called it starts with the argument. You can negate the result to find the strings that don't start with the argument. To do this, apply the ! operator before the argument of the where expression. Here is an example:
private void Exercise_Load(object sender, EventArgs e)
{
var name = new[]
{
"Hermine", "Patrick", "Hank", "Bertine",
"Julius", "Thomas", "Jeannette", "Patricia",
"Henriette", "Raul", "David", "Paulette"
};
var names = from n
in name
where !n.StartsWith("P")
select n;
foreach (var member in names)
lbxNames.Items.Add(member);
}
This would produce:
To make the expression easy to read, you should include it in parentheses. Here is an example:
private void Exercise_Load(object sender, EventArgs e) { var name = new[] { "Hermine", "Patrick", "Hank", "Bertine", "Julius", "Thomas", "Jeannette", "Patricia", "Henriette", "Raul", "David", "Paulette" }; var names = from n in name where !(n.StartsWith("P")) select n; foreach (var member in names) lbxNames.Items.Add(member); }
Checking the Ending Sub-String
To get a list of strings that end with a certain letter or sub-string, you can call the String.EndsWith() method. Here is an example:
private void Exercise_Load(object sender, EventArgs e)
{
var name = new[]
{
"Hermine", "Patrick", "Hank", "Bertine",
"Julius", "Thomas", "Jeannette", "Patricia",
"Henriette", "Raul", "David", "Paulette"
};
var names = from n
in name
where n.EndsWith("ette")
select n;
foreach (var member in names)
lbxStrings.Items.Add(member);
}
This would produce:
To negate this operation, apply the ! operator to it.
Checking the Existence of a Sub-String
To get a select list of strings that contain a certain symbol or a sub-string, you can call the String.Contains() method in your query statement. Here is an example:
private void Exercise_Load(object sender, EventArgs e)
{
var name = new[]
{
"Hermine", "Patrick", "Hank", "Bertine",
"Julius", "Thomas", "Jeannette", "Patricia",
"Henriette", "Raul", "David", "Paulette"
};
var names = from n
in name
where n.Contains("au")
select n;
foreach (var member in names)
lbxStrings.Items.Add(member);
}
This would produce:
Because the String.Contains() method is Boolean, to negate its result, you can precede it with the ! operator.
Date/Time Values in LINQ
Introduction
The .NET Framework supports date and time values through various structures. This allows you to use date and time values in your queries.
Selecting from a List of Date/Time Values
You can involve date or time values in LINQ. To start, create a list, such as an array, using the structure of your choice. In your select statement, access the list as we have done so far. Here is an example:
namespace Exercises { public partial class Exercise : Form { public Exercise() { InitializeComponent(); } private void Exercise_Load(object sender, EventArgs e) { DateOnly[] daysWork = new[] { new DateOnly(2022, 11, 14), new DateOnly(2022, 11, 15), new DateOnly(2022, 11, 23), new DateOnly(2022, 11, 24), new DateOnly(2022, 11, 25) }; var work = from days in daysWork select days; foreach (DateOnly d in work) { lbxDaysWork.Items.Add(d.ToString()); } } } }
This would produce:
In the above example, we used a list of DateOnly values. In the same way, you can work with lists of TimeOnly and DateTime values. All three structures are equipped with properties and methods you can use in your queries. Here is an example that produces the names of the week days:
namespace Exercises { public partial class Exercise : Form { public Exercise() { InitializeComponent(); } private void Exercise_Load(object sender, EventArgs e) { DateOnly[] daysWork = new[] { new DateOnly(2022, 11, 14), new DateOnly(2022, 11, 15), new DateOnly(2022, 11, 23), new DateOnly(2022, 11, 24), new DateOnly(2022, 11, 25) }; var work = from days in daysWork select days; foreach (DateOnly d in work) { lbxDaysWork.Items.Add(d.DayOfWeek); } } } }
This would produce:
Selecting with Conditions
The DateOnly, the TimeOnly, and the DateTime structures all support all logical operators: ==, !=, <, <=, >, >=, !, is, and not. You can use them in your LINQ statements or when accessing the query result.
|
|||
Previous | Copyright © 2008-2023, FunctionX, Inc. | Wednesday 15 September 2021 | Next |
|