Work with LINQ in C#
Objective: Work with LINQ in C#.
LINQ or Language Integrated Query, is the query language similar to sql but it was build into C# for retrieve data in collection.
To use LINQ in C# you must use a name space called System.Linq.
Before using LINQ, I will create an array of numbers.
To retrieve a data we need to access a source, which is our array/numbers then we use Any bult-in query method. This method take a delegate func<T,bool> so I will use lambda expression for this.
Note: T will be the parameter of collection and bool will be used to check for condition of the parameter.
To access this result, I will assign to the variable and debug it.But remember the result will be according to delegate type func<T,bool> which go through Any method , so result will be true or false if the value exists or not.
Simple version of Any Query method
We can use another method which is much simpler than Any called Contain. Inside this method goes the element of collection you want to check if available.
Using Distinct method of the Linq library.
This method remove all duplicate of the collection, we can use this to filter element and store the new collection with no duplicate.
To filter trough each number i will use foreach, using result as new collection without duplicate.
Using Where method.
This method allow us to return Enumerable which is collection interface/collection based on some logic.
Using OrderByDescending Method.
We can use OrderByDescending after where or Any method, adding dot and type OrderByDescendig the collection will be sorted by Descending order from high to low value. This method don't need logic I will pass element using lambda to sort through all element and return element.
To reverse this OrderByDescending we add another method called Reverse method after OrderByDescending.
Find Average using built-in method, We use a method called average.
How to Read and Convert Query Syntax to Linq method.
Lets look this example from Microsoft, this query is similar to sql , we have a collection of number then access each element from collection then they use where to give condition and last we select the result.
Lets convert to method syntax!
We use where method to add filter using logic, I will use lambda operation to go through each element and check if it successful satisfy a condition.
Best practice
It is recommended to use method syntax since are easy to grasp the syntax.
Some logic need you to use query syntax to perform complex logic
See you into the next one.