DEV Community

Simon Foster
Simon Foster

Posted on • Originally published at funkysi1701.com on

LINQ

What is LINQ?

LINQ is an acronym for Language Integrated Query, which describes where it’s used and what it does. The Language Integrated part means that LINQ is part of programming language syntax. In particular, both C# and VB are languages that ship with .NET and have LINQ capabilities.

How do I use LINQ in my C# code?

To use LINQ the first thing you need to do is add the LINQ using statement.

using System.Linq;

Enter fullscreen mode Exit fullscreen mode

In your code you need a datasource, for this example I am going to use a simple array, but it can be anything eg SQL, XML etc

int[] data = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

Enter fullscreen mode Exit fullscreen mode

Next you need a LINQ query. (Note I know the Q in LINQ means query, so I have just written query query, if you are one of those people who hates seeing PIN number you might not like this blog post.) A LINQ query is very similar to a T-SQL query, so if like me you are good with databases this should make sense to you.

In T-SQL you can have:

SELECT num
FROM data
WHERE num = 1

Enter fullscreen mode Exit fullscreen mode

In LINQ this becomes:

var query =
from num in data
where num == 1
select num;

Enter fullscreen mode Exit fullscreen mode

Finally you need to do something with the query you have written. I am just going to print the results of my query to console.

foreach (var num in query)
{
  Console.Write(num);
}

Enter fullscreen mode Exit fullscreen mode

What other SQL like syntax can I use?

In T-SQL you can control ordering using ORDER BY, LINQ has a similar syntax orderby

orderby num descending

Enter fullscreen mode Exit fullscreen mode

In T-SQL you can use GROUP BY, to do something similar with LINQ

group num by num.Type into type
select type


foreach (var type in query)
{
  Console.Write(type.Key);
  foreach (var num in type)
  {
    Console.Write(num);
  }
}

Enter fullscreen mode Exit fullscreen mode

JOINS

So you thought joining tables was a SQL Server only thing. Think again you can do this in LINQ

var joinquery =
from cust in customers
join prod in products on prod.CustomerId equals cust.Id
select new { ProductName = prod.Name, CustomerName = cust.CompanyName };

Enter fullscreen mode Exit fullscreen mode

Conclusion

There are loads more LINQ functionality that you can use. While writing this blog I found https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b which has loads of examples of different queries that you can write with LINQ.

This has inspired me to use LINQ more in my code and learn more about the different queries that could be written.

Top comments (0)