You can find some examples on my website using Linq, but today I will show the most simple example using this feature.
First, you need to take a look at the documentation page and read how this works.
This feature uses a query using three distinct steps of a LINQ query operation:
- Obtain the data source
- Create the query
- Execute the query
I create a folder named LinqExample001 and I use this command to create a console application:
1 | dotnet new console |
You don’t need to use install with dotnet because this package is set to default.
My source code example for calculating the average for an array comes with these parts: first is the basic calculation and the second one uses the LINQ feature:
This is the source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | using System; using System.Linq; namespace LinkExample001 { class Program { static void Main(string[] args) { int[] intNumbers = new int[] { 7, 3, 76}; //Using the basic method Syntax var MAverageValue = intNumbers.Average(); Console.WriteLine("Basic method : Average Value = " + MAverageValue); //Using Query syntax from Linq var LinqAverageValue = (from num in intNumbers select num).Average(); Console.WriteLine("Linq method : Average Value = " + LinqAverageValue); } } } |
The result of the running code is this:
1 2 | Basic method : Average Value = 28.666666666666668 Linq method : Average Value = 28.666666666666668 |
The data source is the intNumbers.
You can see the LINQ query uses these words: from, in, select to create query.
The execution of the LINK query is the Average function.