This tutorial will brief you on how to write LINQ Queries in C#
In this tutorial we will show you couple different ways you can write a LINQ queries. We will review query and method syntax as well as a combination of the both.
When using LINQ, the basic syntax is identical to that used in LINQ to SQL and LINQ to XML. These queries can operate on simple in-memory collections. It’s recommended in writing most queries to use query syntax to create query expressions.
Notice below how we use type IEnumerable(T) for our queries. They could also be written using var like this:
| var query = from nam in names.. |
Ok. Let’s look at our example:
// Query A
List<string> names = new List<string>() { John, Harry, Mel, Steffan, Jacob, John};
// The query variable can also be implicitly typed by using var
IEnumerable<string> filteringQuery =
from nam in names
where nam = ’Harry’
select nam;
// Query B
IEnumerable<string> orderingQuery =
from nam in names
where nam = ‘Mel’
orderby nam ascending
select nam;
// Query C
string[] groupingQuery = { "hammer", "nails", "saw", "drill", "screws" };
IEnumerable<IGrouping<char, string>> queryToolGroups =
from item in groupingQuery
group item by item[0]; |
Above displays three query expressions. Query A demonstrates how to filter or restrict by applying conditions with a where clause. This way it return all elements in the source sequence whose values are equal to Harry.
Need help with Windows Dedicated Hosting? Try Server Intellect I'm a happy customer!
Query B demonstrates how to order the returned results.
Query C demonstrates how to group results according to a key. This query returns two groups based on the first letter of the word.
Ok. Let’s go over some Method syntax. Depending on the type of query operation you are using it must be expression as a method call. Some of the most common methods are those that return specific single numeric values (ie Sum, Max, Min, Average, etc..). These methods must always be called last in any query considering that they only represent a single value and cannot server as the source for any additional operations. Here is an example of a method call in a query expression:
List<int> numbers1 = new List<int>() {34, 89, 18, 33, 67, 16, 21, 20, 1, 99 };
// Query D
double average = num1.Average(); |
**This is the only query that executes immediately because it returns a single value, not a generic IEnumerable(T) coolection. In that case, each method itself needs to use foreach inorder to compute its value.
List names2 = new List() { Kaitlyn, Samantha, Mark, Tara, Brooke, Najee};
// Query E
IEnumerable<string> concatenationQuery = names1.Concat(names2); |
If the method has parameters then it is provided in the form of a Lambda expression like so:
List names1 = new List() { Pat, David, Steve, Donna, Ralph};
//Query F
IEnumerable<string> query = names1.Where(x => x.Length > 5).OrderBy(x => x); |
A lambda expression normally takes the form of arguments => expression. The lambda expression is always preceded by the => token. If you have a lambda expression with more than one argument you must enclose the arguments in parentheses delimited by a comma./p>
The following example displays that all of the queries above can be written using implicit typing with var:
/// var is used for convenience in these queries
Query D:
var average = numbers1.Average();
Query E:
var concatenationQuery = names1.Concat(names2);
Query F:
var query = names.Where(x => x.Length > 5).OrderBy(x => x); |
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.
Ok, finally let’s combine the two and discuss mixed query and method syntax. /p>
Below is an example that illustrates how to use method syntax on the results of a query clause. This way you are able to just enclose the query in parentheses, and then apply the dot operator and call the method. Check out this example:
/// Query G
List<int> numbers1 = new List<int>() {34, 89, 18, 33, 67, 16, 21, 20, 1, 99 };
List<int> numbers2 = new List<int>() {45, 303, 18, 93, 57, 23, 3, 21, 11, 6, 101, 149 };
// Using a query expression with method syntax
int numCntA =
(from num in numbers1 where num < 11 || num > 78
select num).Count();
// Create a new variable to store the method call result =
from num in numbers2
where num < 11 || num > 78
select num;
int numCntB = numQuery.Count(); |
In the code block above, Query G returns a count of the numbers whose value is between 11 and 78. Typically, it is better to use the second expression to store the result of the method call. This way the query is less likely to be confused with the results of the query. p>
The reason that Query G returns a single value is because it’s not a collection, therefore it should execute immediately.
In tIn this example below it can also be written by using implicit typing with var:
| var numCnt = (from num in numbers... |
or in a method:
| var numCnt = numbers.Where(n => n < 11 || n > 78).Count(); |
and can be written using implict typing:
| int numCnt = numbers.Where(n => n < 11 || n > 78).Count(); |
We chose Server Intellect for its dedicated servers, for our web hosting. They have managed to handle virtually everything for us, from start to finish. And their customer service is stellar.