Learn how to write LINQ Queries in C#


Server Intellect


Learn how to write LINQ Queries in C#

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.



Comments
Ibrahim said:

how to update List items without writing foreach loop using linq

suppose you are having Customer List ex:List<Customer> . Customer class having FirstName and LastName properties..

Normal Way to update FirstName of each Customer is

for each(Customer c in CustomerList)

{

c.FirstName ="My Custom Name";

}

how do you write this logic in Linq?

Note that i dont want to add it in another new List. i want the same functionality as above for loop was done.

Thanks for any help

Posted 03/27/2010 at 5:33 AM
Jai Baba Ramdev said:

jaibabaramdev

jaibabaramdev

jaibabaramdev

jaibabaramdev

jaibabaramdev

jaibabaramdev

jaibabaramdev

jaibabaramdev

Posted 04/29/2010 at 2:30 AM
Oppapers.com said:

This article is very useful for computer students and programmers. This article contains tutorial to write LINQ Queries in C#. Here the author shows us two different methods to write LINQ Queries in C#. LINQ is a consistent programming model that enables us to query the data from various data sources. It is now mostly used with C# to design web 2.0 applications. The explanations of these two different methods are done with examples so that we can easily understand it. Also step by step evaluation of each query is also there to help us grasp it fast. Also it will help us to clear all doubts that arise in our mind about these methods. All computer enthusiasts and programmers will definitely waiting for further articles from the author.

Posted 05/04/2010 at 9:39 PM
casino en ligne said:

It should be noted that LINQ queries take a non-trivial performance hit over more manual solutions. For things like your first example (a simple array), a foreach loop would probably be better. When you get into more complex tasks, like complicated queries with relational DBs for example, the simplicity of LINQ starts to out-weigh its speed issues...

Posted 07/08/2010 at 3:51 AM
Gifts said:

This article contains tutorial to write LINQ Queries in C#. Here the author shows us two different methods to write LINQ Queries in C#. LINQ is a consistent programming model that enables us to query the data from various data sources. It is now mostly used with C# to design web 2.0 applications. The explanations of these two different methods are done with examples so that we can easily understand it.

Posted 07/10/2010 at 2:09 AM
Prostate Cancer Treatment said:

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.Thanks

Posted 07/20/2010 at 6:32 AM
Hydraulic jacks said:

i like this method .. its easy and understanable.... last time i found that.. but that was so long and complicated

Posted 07/22/2010 at 4:17 PM
Hydraulic jacks said:

Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language (also in Visual Basic and potentially any other

Posted 07/22/2010 at 4:20 PM
Hydraulic jack said:

For a developer who writes queries, the most visible "language-integrated" part of LINQ is the query expression. Query expressions are written in a declarative query syntax introduced in C# 3.0.

Posted 07/22/2010 at 4:21 PM
Attorney said:

It should be noted that LINQ queries take a non-trivial performance hit over more manual solutions. For things like your first example (a simple array), a foreach loop would probably be better. When you get into more complex tasks, like complicated queries with relational DBs for example, the simplicity of LINQ starts to out-weigh its speed issues...Thanks

Posted 07/26/2010 at 3:31 AM
Attorney said:

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...Thanks

Posted 07/26/2010 at 7:40 AM
Fold Up Bikes said:

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..)

Posted 07/30/2010 at 5:54 AM
Holiday Costumes said:

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...Thanks

Posted 07/31/2010 at 4:49 PM
Piano Lessons said:

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.

Posted 08/02/2010 at 2:57 PM
Photo Calendars said:

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.

Posted 08/04/2010 at 9:35 AM
Live Food said:

For a developer who writes queries, the most visible "language-integrated" part of LINQ is the query expression. Query expressions are written in a declarative query syntax introduced in C# 3.0.

Posted 08/08/2010 at 3:23 PM
simulation assurance auto said:

I am very interested in your article, I think your articles are so interesting that I need more information, go is berkaya and I will always support you. I say many thanks to you.

Posted 08/09/2010 at 4:57 AM
How to Salsa Dance said:

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>

Posted 08/09/2010 at 12:31 PM
Insurance said:

things like your first example (a simple array), a foreach loop would probably be better. When you get into more complex tasks, like complicated queries with relational DBs for example, the simplicity

Posted 08/15/2010 at 3:29 PM
travel said:

Th4t be an epic da shizzi4 post, th4nkie 4it & in da futures we'll be seeing more of it

Posted 08/18/2010 at 2:50 PM
cruises said:

We7ll I8be dat9 ogr6e speekie da speekie, gratz & than4x

Posted 08/18/2010 at 2:51 PM
flight center said:

heb7e sh8at be th34nkie 4it on da posting left & righ8ty

Posted 08/18/2010 at 2:51 PM
online roulette said:

I will recommend my friends to read this.I will bookmark your blog and have my children check up here often.I am quite sure they will learn lots of new stuff here than anybody else!....

Posted 08/20/2010 at 7:09 AM
chicken said:

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:

Posted 08/26/2010 at 7:54 AM
coach outlet said:

coach outlet

Posted 08/26/2010 at 1:57 PM
louis vuitton bags said:

louis vuitton bags

Posted 08/26/2010 at 1:58 PM
xiaopohai said:
Posted 08/26/2010 at 9:18 PM
Nisha said:

very nice article .....

I want name which is started from some char like s from string array then how should i write query.....

Help me............

Posted 09/01/2010 at 7:36 AM
best online casino sites said:

For a developer who writes queries, the most visible "language-integrated" part of LINQ is the query expression. Query expressions are written in a declarative query syntax introduced in C# 3.0.

Posted 09/03/2010 at 6:31 AM

Leave a Comment