When writing applications you have many ways to perform the same task. In some cases, performing the task in a particular way has a benefit. For example, if you use a specific approach, the code might run faster, be more reliable, or provide additional security. However,developers often use an approach to coding that’s simply comfortable or familiar.
The btnLINQ_Click() event handler could use several different methods to obtain the same results—none of which is superior to any other. For example, instead of converting the outputto an array before displaying the message box, you could create the array directly as part of the LINQ statement like this:
private void btnLINQ_Click(object sender, EventArgs e)
{
// Create the query.
var Output = (from String TheEntry in TestArray select TheEntry.Substring(0, 3)).ToArray<String>();
// Display one of the results.
MessageBox.Show(Output[2]);
}
This approach would work best if you need the array form of Output in several different places. In fact, you don’t have to convert Output to an array at all. You can use the ElementAt() method instead like this:
private void btnLINQ_Click(object sender, EventArgs e)
{
// Create the query.
var Output = from String TheEntry in TestArrayselect TheEntry.Substring(0, 3);
// Display one of the results.
MessageBox.Show(Output.ElementAt<String>(2));
}
This approach might be a little less readable than the approach used in the previous example,
but the results are precisely the same. The point is that all three methods work and it’s up to you to choose which method works best for you.
No comments:
Post a Comment