Whether you have been working with .NET for a while or are just getting started, you have almost certainly run into LINQ (Language Integrated Query). It is one of those tools that, once you discover it, makes you wonder how you ever lived without it. LINQ allows me to query and manipulate data—whether in lists or databases—in an incredibly fluid way, almost as if talking directly to the data, without having to write raw SQL queries whenever working with a database. Let’s admit it: that makes life a lot easier when dealing with data in your code.
Why do I love LINQ and use it all the time? For three main reasons:
- Readable: The code reads almost like plain English, which makes it much easier to understand and maintain. There is nothing worse than revisiting code after several months, or reviewing someone else’s, and having no idea what it actually does.
- Reusable: I can build modular, dynamic queries—like Lego pieces—and adapt them to different scenarios without starting from scratch.
- Type-safe: Compile-time checking saves me from those silly runtime errors you only discover when everything crashes in production.
The best part about LINQ is that it isn’t limited to database ORMs like Entity Framework or LINQ to SQL. It also works seamlessly with in-memory collections, XML files, and even external services. In this short guide, I want to share a few tips I have learned and use regularly to get the most out of LINQ, writing cleaner, more efficient, and easier-to-follow code. These are practical techniques so that your code doesn’t just work, but also looks elegant. It is a handy reference sheet I am sharing for support, something you can look back on if you need details about LINQ or something I can link to from future posts. Let’s dive in.
Best Practices in LINQ
These examples come from an application I called SimpleEmployeesApp, a small .NET project I published on GitHub. There, I put these LINQ concepts into practice with Entity Framework Core, using an in-memory database and some sample data I prepared to illustrate everything. If you’d like, you can download it, tinker with it, and experiment with the examples at your own pace. Let’s move on.
1. Select only the data you actually need
One of the first things I learned is that when querying a database, fetching more data than necessary is like going to the supermarket for coffee and leaving with a full cart. It hurts performance and wastes memory. That is why I use Select() to fetch only the fields I am going to use.
Take a look at this unoptimized example:
var empleados = context.Empleados.ToList();
var nombres = empleados.Select(e => new { e.Nombre, e.Apellido });
Here, I first load all employee data into memory and then filter it. That is a waste of resources. Now, look at how I do it in an optimized way:
var nombresOptimizado = context.Empleados
.Select(e => new { e.Nombre, e.Apellido })
.ToList();
Here, I first load all employee data into memory and then filter it. That is a waste of resources. Now, look at how I do it in an optimized way:
var nombresOptimizado = context.Empleados
.Select(e => new { e.Nombre, e.Apellido })
.ToList();
In this case, the database does the heavy lifting of selecting only first and last names before sending them over to memory. Much faster and lighter, don’t you think?
2. Use IQueryable instead of IEnumerable for databases
I admit that at first, I didn’t clearly understand the difference between IEnumerable and IQueryable, but once it clicked, there was no going back. The key lies in where the filters are evaluated:
IEnumerable: Loads everything into memory and filters afterward.IQueryable: Translates the query into SQL and filters directly in the database.
A less efficient example:
var empleadosEnum = context.Empleados.ToList(); // Trae todos los datos a memoria
var filtradosEnum = empleadosEnum.Where(e => e.Salario > 5000).ToList();
Here, I bring all employees into memory and then filter. In contrast, using IQueryable:
var filtradosQuery = context.Empleados
.Where(e => e.Salario > 5000)
.ToList();
The filter executes directly in the database, and only employees with a salary greater than 5000 ever reach my application. It is a small change that makes a huge difference.
3. Take advantage of deferred execution
LINQ has a great feature: deferred execution. This means the query does not actually execute until you genuinely need the data. It is like preparing a to-do list, but not starting on it until you are completely ready.
For example:
var consultaDiferida = context.Empleados.Where(e => e.Salario > 5000);
consultaDiferida = consultaDiferida.OrderBy(e => e.Nombre); // Todavía no pasa nada
var resultadoInmediato = consultaDiferida.ToList(); // Aquí sí se ejecuta
I can build the query step by step, and only when I call ToList() or something like FirstOrDefault() does LINQ actually hit the database. This is ideal for dynamic queries.
4. Choose the right join
When I need to combine data from multiple tables, joins are essential. But you have to know which one to pick:
Inner Join: Only brings back records that match in both tables. For example, employees with assigned departments:
var innerJoin = from e in context.Empleados
join d in context.Departamentos on e.DepartamentoId equals d.Id
select new { e.Nombre, d.NombreDepartamento };
Left Join: Retrieves all records from the left table, even if they have no matching record on the right. Perfect for including employees without an assigned department:
var leftJoin = from e in context.Empleados
join d in context.Departamentos on e.DepartamentoId equals d.Id into gj
from subD in gj.DefaultIfEmpty()
select new { e.Nombre, NombreDepartamento = subD.NombreDepartamento ?? "Sin Departamento" };
Choosing the right join ensures I get exactly what I need.
5. Use extension methods for cleaner code
var empleados = context.Empleados.ToList();
var filtrados = new List<Empleado>();
foreach (var emp in empleados)
{
if (emp.Salario > 5000)
filtrados.Add(emp);
}
filtrados.Sort((e1, e2) => e1.Nombre.CompareTo(e2.Nombre));
With this:
var filtradosOptimizado = context.Empleados
.Where(e => e.Salario > 5000)
.OrderBy(e => e.Nombre)
.ToList();
The second version is shorter, more expressive, and easier to maintain. It is not magic—it is LINQ at its best.
6. Implement pagination for large datasets
If you have ever had to display thousands of records in a table, you know that loading them all at once is a nightmare. That is why I use Skip() and Take() to paginate. For example, to fetch the second page with 10 employees:
int pagina = 2;
int tamañoPagina = 10;
var paginaEmpleados = context.Empleados
.OrderBy(e => e.Id) // Siempre ordenar para paginación consistente
.Skip((pagina - 1) * tamañoPagina)
.Take(tamañoPagina)
.ToList();
This keeps my application fast and scalable.
Additional Tips
Here are a few extra tips that have helped me more than once:
Use AsNoTracking() for read-only queries: If I only need to read data and will not be modifying it, AsNoTracking() in Entity Framework reduces memory consumption:
var empleados = context.Empleados.AsNoTracking().ToList();
Asynchronous operations: Database queries can take time, so I use ToListAsync() to avoid blocking my application:
var empleados = await context.Empleados.ToListAsync();
If you noticed, I didn’t use ToListAsync() in these examples because I am working with an in-memory database; however, if you are working with an actual database server, I strongly recommend using it.
Inspect performance: Tools like SQL Server Profiler or Entity Framework logging help me spot slow queries and optimize them.
In summary, LINQ is a powerful tool in .NET that makes my code cleaner, more efficient, and easier to maintain. By applying these practices, I have achieved faster queries and more robust applications. I hope this guide proves useful in your projects. The key is to practice and experiment, so don’t be afraid to test things out and adjust them to your needs. Remember, if you want to inspect the code we used, you can check it out in the example’s repository.
If you have questions or want to share how you use LINQ, leave a comment on the blog! I would love to chat about it. And if you found it helpful, bookmark this link—I’ll be referencing it in upcoming articles. Keep on coding!