It can even be used to query data structures inside you Razor templates.
You should always filter data before using them
Let me first start by stressing that even if you have the option to do filtering and querying on the data of your code, you should always filter when you request the data from say a database.
You should not get “all data” from the database and then let Linq come to rescue in your code filtering out the data which you really need.
That said, Linq lets you do filtering, sorting and querying at runtime offering you great options to handle the data at hand.
I am not a master at Linq
Also I need to stress out that I am writing this as a novice at Linq, I have close to none experience working with it, but perhaps that is what makes my writing great, cause you be at that exact came level :–)
I for one finds the syntax strange: You seem to mix a sort of SQL syntax right inside your code, spreading across multiple lines – I find that strange, but it works.
The output is all the numbers which can be divided with 2.
0 2 4 6
Method based query and SortBy
The same could be achieved using a method based query syntax like this:
This example has also added the
OrderBy which in this case will sort the list based on a lookup in a
That way it is sorted alphabetically too, pretty nice.
Elisabeth – Mogens – Palle – Sten –
Storing in iNummerable and desc sorting
This third variant stores the filtered data in a
IEnumerable variable. That way it is cached which can be usefull some times for performance.
In this case I want to return the number of found results, and therefore need to be able to write out a count. As I store the filtered data in a variable I can simply write the
.Count on the variable.
I also use another sort order by using
Sten – Palle – Mogens – Elisabeth –
Which datatypes allows Linq queries?
So where can you use it – on which data types can you use Linq? Well I am not 100 % sure, but it seems that the data types found here: System.Collections.Generic namespace can be used.