10.1-LINQ
File Location
Right click on your solution
Go to Add > New Project and select Console App (.NET Framework)
Name it
DateTime
Discussion
LINQ or Language-Integrated Query is a powerful query language used with C# to query different data sources. LINQ is a great way to interact with your future databases.
LINQ is a query language that works with multiple languages other than C#. SQL is a query language used to save and retrieve data from a database. Similarly, LINQ is a query syntax used to save and retrieve data from different data sources like collections, databases, XML, and web services.
LINQ can be used to simplify cumbersome code that foreach
and for
loops can add sometimes. Let's compare. Let's make an array of employees and perform the same functions with a foreach
loop and then do the same with a LINQ query.
Using a foreach
loop
The above code will grab all the employees whose age is between 25 and 40.
Now with a LINQ query and delegate
Discussion
We have the advantage of delegate
in finding employees with any criteria. You don't have to use a for
loop to find employees using different criteria. For example, you can use the same delegate
function to find a employee whose StudentId
is 5 or whose name is Bill, as below:
We just need the loop to loop through the collection but not to identify criteria.
Lambda Expression
You can make your code even more compact and readable with the lambda expression =>
. Lambda is a great resource with LINQ queries to get the results you want in a single statement.
The example below shows how you can use LINQ query with lambda to find a particular employee(s) from the employee collection.
Student[] oldStudents = studentArray.Where(s => s.Age > 30).ToArray();
Student billStudents = studentArray.Where(s => s.StudentName == "Bill").FirstOrDefault();
With this expression you can totally get rid of delegate
and your StudentExtension
class to get the information you need. Way less code and just as powerful. To print the information to the console you would still need a forloop
but with most of your later applications, you won't need to print everything to the console.
Challenge
Make a list of different cars, including BMW's and Hyundai's, with a price range from $8,000 - $30,000.
Make sure to make a class with corresponding properties.
Using LINQ queries
Find all the BMW's
Find all the cars less than $10,000
Find all the cars that cost less than $15,000 and are Hyundai's.
Answers
Optional Reading
Learn more about LINQ.
Learn more about lambda expressions.
Last updated