Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Task 2 – Querying a Generic List of Integers

1. In Solution Explorer, double click Program.cs

2. Create a new method that declares a populated collection of integers (put this method in the Program class):

class Program

{

static void Main(string[] args)

{

}

static void NumQuery()

{

var numbers = new int[] { 1, 4, 9, 16, 25, 36 };

}

}

 

Notice that the left-hand side of the assignment does not explicitly mention a type; rather it uses the new keyword var. This is possible due to one of the new features of the C# 3.0 language, local variable type inference. This feature allows the type of a local variable to be inferred by the compiler. In this case, the right-hand side creates an object of type Int32[]; therefore the compiler infers the type of the numbers variable to be Int32[]. This also allows a type name to be specified only once in an initialization expression.

 

3. Add the following code to query the collection for even numbers

 

static void NumQuery()

{

var numbers = new int[] { 1, 4, 9, 16, 25, 36 };

 

var evenNumbers = from p in numbers

where (p % 2) == 0

select p;

}

 

In this step the right-hand side of the assignment is a query expression, another language extension introduced by the LINQ project. As in the previous step, type inference is being used here to simplify the code. The return type from a query may not be immediately obvious. This example returns System.Collections.Generic.IEnumerable<Int32>; move the mouse over the evenNumbers variable to see the type in Quick Info. Indeed, sometimes there will be no way to specify the type when they are created as anonymous types (which are tuple types automatically inferred and created from object initalizers). Type inference provides a simple solution to this problem.

 

4. Add the following code to display the results:

static void NumQuery()

{

var numbers = new int[] { 1, 4, 9, 16, 25, 36 };

 

var evenNumbers = from p in numbers

where (p % 2) == 0

select p;

 

Console.WriteLine("Result:");

foreach (var val in evenNumbers)

Console.WriteLine(val);

}

 

Notice that the foreach statement has been extended to use type inference as well.

 

5. Finally, add a call to the NumQuery method from the Main method:

static void Main(string[] args)

{

NumQuery();

}

 

6. Press Ctrl+F5 to build and run the application. A console window appears. As expected all even numbers are displayed (the numbers 4, 16, and 36 appear in the console output).

7. Press any key to terminate the application.


Date: 2015-02-03; view: 848


<== previous page | next page ==>
Lab Objective | Task 3 – Querying Structured Types
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.011 sec.)