| Start |
|---|
| Using LINQ to Objects in C# A simple SELECT query in Linq In the example above, an array of strings (cars) is used as a collection of objects to be queried using LINQ. In a LINQ query, the from clause comes first in order to introduce the data source (cars) and the range variable (car). When the query is executed, the range variable will serve as a reference to each successive element in cars. Because the compiler can infer the type of car, you do not have to specify it explicitly When the above code is compiled and executed, it produces the following result:
SELECT with a WHERE Clause The WHERE clause is used to query the string array (cars) to find and return a subset of array which satisfies the WHERE clause. When the above code is compiled and executed, it produces the following result: Generating an Ordered List Sometimes it is useful to sort the returned data. The orderby clause will cause the elements to be sorted according to the default comparer for the type being sorted. When the above code is compiled and executed, it produces the following result: Working with a custom type In this example, a typed list is created, populated, and then queried When the above code is compiled and executed, it produces the following result: Until now the examples don't seem amazing as one can just iterate through the array to do basically the same. However, with the few examples below you can see how to create more complex queries with LINQ to Objects and achieve more with a lot less of code. In the example below we can select cars that have been sold over 60000 units and sort them over the number of units sold: When the above code is compiled and executed, it produces the following result:
In the example below we can select cars that have sold an odd number of units and order them alphabetically over its name: When the above code is compiled and executed, it produces the following result:
|
| How LINQ to Object executes queries LINQ queries do not execute immediately. When you are building the query you are simply storing the query for future execution. Only when you actually request to iterate the query is the query executed (e.g. in a for loop, when calling ToList, Count, Max, Average, First, etc.) This is considered deferred execution. This allows you to build up the query in multiple steps, potentially modifying it based on conditional statements, and then execute it later only once you require the result. Given the code: The example above only stores the query into The Some LINQ methods will also trigger the query execution, Be aware that it is possible for you to iterate across the query multiple times if you call multiple LINQ functions on the same query. This could give you different results at each call. If you only want to work with one data set, be sure to save it into a list or array. |
Read Article
https://develop.horje.com/learn/1434/reference