LINQ without the magic trick
Administrator - 10/06/2026
LINQ gave me one consistent way to filter, reshape and compose data across ordinary C# collections, reflection results and Entity Framework queries. The useful part is knowing what will run, where it will run and when it will run.
Tags: C# .NET LINQ EntityFrameworkCore expressiontrees IQueryable CMS
A practical account of how I used LINQ in KUUT. Project period: August 2022 to present.
LINQ is one of the reasons I took to C#. It lets me describe the result I want without writing the plumbing for every loop, temporary list and conditional. Used well, a query reads as a compact explanation of the job. Used carelessly, it conceals database calls, repeated enumeration and a surprising amount of work behind a line that looks almost decorative.
I have managed both.
KUUT uses LINQ in several different ways. There are ordinary in-memory queries, Entity Framework Core queries that become SQL, reflection pipelines that inspect the application itself, and an expression-tree experiment that builds a filter from a property name at runtime. The syntax looks similar in each case. The behaviour is not necessarily similar at all.
This is where LINQ becomes interesting.
The ordinary case
The simplest examples are often the best. The administration code receives a set of role choices, keeps the selected ones, extracts their identifiers, matches those identifiers against the available roles and finally selects their names. In method syntax, the shape is immediately visible:
var selectedRoleIds = model
.Where(item => item.Selected)
.Select(item => item.RoleId)
.ToList();
var selectedRoleNames = roles
.Where(role => selectedRoleIds.Contains(role.Id))
.Select(role => role.Name)
.ToList();
There is nothing clever here, which is precisely why it works. Each operator does one recognisable job. The first query turns UI state into a list of IDs. The second turns those IDs into names. A foreach loop would also be valid, but it would make the mechanics of building the lists more prominent than the selection itself.
This is the first thing I like about LINQ: it gives transformations a vocabulary. Where, Select, OrderBy, Take, Any and FirstOrDefault say what is happening without requiring a comment to translate the code back into English.
That does not mean every loop should be converted. A loop is often clearer when the body has several side effects, when state changes at each step, or when the operation needs early exits that would become tangled inside lambdas. LINQ is strongest when data flows through a sequence of transformations. It is much less attractive when it is being used to disguise a procedure.
Querying the application itself
My favourite use in KUUT is the sitemap builder. Rather than maintaining a second list of every route that belongs in the sitemap, controller methods can carry a custom sitemap attribute. At startup the application scans its own assembly and builds a route description from those marked methods.
The core query does this:
return assembly.GetTypes()
.Where(type => typeof(Controller).IsAssignableFrom(type)
|| typeof(PageModel).IsAssignableFrom(type))
.SelectMany(type => type.GetMethods(
BindingFlags.Instance |
BindingFlags.DeclaredOnly |
BindingFlags.Public))
.Where(method => !method.GetCustomAttributes(
typeof(CompilerGeneratedAttribute), true).Any())
.Where(method => method.GetCustomAttributes(
typeof(SitemapUrlAttribute), true).Any())
.Select(method => new LinqObj(
method.DeclaringType.FullName,
method.DeclaringType.Name,
method.Name,
method.GetCustomAttribute<SitemapUrlAttribute>()))
.ToList();
It starts with types, filters them, flattens their methods with SelectMany, filters again and projects the remaining methods into a small data object. The query is a pipeline, but it is also an outline of the feature. I can read down it and see the narrowing process.
Reflection is not free, so I would not run this on every request. KUUT builds the sitemap at application startup, and again only when CMS content changes, so the cost is bounded and the result can be reused. Move the same query into a request hot path and the judgement changes: “elegant” code can still be a bad decision.
The point where IEnumerable becomes IQueryable
LINQ over a List<T> generally works with IEnumerable<T>. The lambdas become delegates and execute in the .NET process against objects already in memory.
Entity Framework normally exposes IQueryable<T>. In that case the query is being assembled as a description. EF examines that description and translates supported operations into SQL for the database provider. The call to ToListAsync, FirstOrDefaultAsync, CountAsync or another terminal operation is usually where the query is sent.
That separation is extremely useful. KUUT can start with BlogPosts, add a filter, choose how much related data to include, select one result and execute the whole thing as a single composed operation:
var post = await BlogPosts
.AddFilter(property, value)
.IncludeDepth(depth)
.FirstOrDefaultAsync();
It also creates traps. A method that works perfectly against a local collection might not be translatable by the provider. Moving to AsEnumerable() too early can pull far more data into memory than intended. Calling ToList() in the middle fixes the result at that point and prevents later operators from being translated into the same database query.
The type tells me which world I am in, but only if I pay attention to it.
Deferred execution is useful until it is surprising
Most LINQ operators that return a sequence use deferred execution. Defining the query does not necessarily run it. Enumeration runs it.
This allows a query to be built in stages. It also means that enumerating it twice may repeat the work and may produce different results if the source changed in between. With Entity Framework, two enumerations can mean two database queries. With an in-memory source, it can mean rerunning an expensive transformation.
Materialisation should therefore be a decision, not punctuation added by habit. I use ToList when I want a stable result that will be read more than once, when the next operation needs a list, or when I want execution to happen at a clear boundary. I leave a query deferred when further composition is valuable and the eventual consumer will enumerate it once.
There is no prize for keeping everything lazy. There is also no prize for turning every query into a list immediately.
Building a predicate at runtime
The CMS needed to retrieve several content types by different properties: a blog post by slug, an author by application-user ID, a page by title. I experimented with a generic filter that accepts the entity type, property name and value, then constructs an expression tree equivalent to:
entity => entity.SomeProperty == value
An expression tree represents code as data. Instead of compiling the lambda straight into a delegate, the code creates nodes for the parameter, property access, constant and equality comparison. It then wraps those nodes in an Expression<Func<T, bool>> and passes the result to Where.
Because Entity Framework receives the structure of the expression, it can translate that comparison into SQL. A compiled Func<T, bool> would be opaque to the provider and would normally imply in-memory execution instead.
This taught me a great deal about what LINQ providers actually consume. It also produced an API I would tighten before reusing elsewhere.
The property is supplied as a string. If the name is wrong, the compiler cannot help. The current code checks some types, but it should first resolve the property deliberately, reject unknown or unsupported properties, handle nullable conversions and return a useful error. The separate AddFilter overloads for each CMS entity also repeat themselves. A constrained generic extension or an explicit map of permitted fields would make the boundary clearer.
It is a good portfolio example because it includes both the idea and the criticism. I built a dynamic query, saw why it worked, and can now see the places where flexibility became avoidable runtime risk.
What LINQ does well
LINQ is excellent when it keeps the operation close to the data and makes the transformation readable. It lets me compose filters without a thicket of nested conditionals. The generic operators work across collections and query providers, while the type system carries the shape of each stage. Projection is particularly useful: I can return only the fields or object shape that the caller needs instead of hauling whole entities through the application.
It also makes code review easier when the query remains straightforward. A reviewer can see that private posts are excluded, results are ordered by update time and only a requested number are taken. Those are meaningful business rules, not loop machinery.
Where I stop trusting the pretty syntax
The main disadvantage is that compactness can hide cost. A short query can issue poor SQL, enumerate the same source repeatedly, allocate several intermediate collections or load a large related graph. Include can multiply rows. Contains can become a large SQL IN expression. A predicate that calls an ordinary C# method might not translate at all.
Debugging therefore has to cross the abstraction. For database queries I need to inspect generated SQL and timings, not judge performance from the number of C# lines. For in-memory work I need to understand the size of the source and how many passes the operators require. For either form, I need tests around empty input, missing values and ordering.
LINQ is not a replacement for understanding the underlying operation. It is a very good language for expressing that understanding.
That is why I still enjoy using it. At its best, it removes noise without removing intent. At its worst, it makes an expensive mistake look immaculate. The useful skill is knowing which one I have written.
LINQ external execution
LINQ is basically about retrieval, or was designed to be, but in a very few cases you can integrate external execution. Say you have a select statement: you can then call an action that continues the overall process. I learned this by experimenting and was never sure of it because it was, well, 'odd'. But after doing some research I discovered that some developers do take advantage of this, including Jon Skeet, who said on Stack Overflow that this was not an invalid approach and, in the right situation, can be an elegant way to solve particular problems and improve the code's readability. Just, as I said, not very often.