Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

LINQ Select: Return Needed Fields with Anonymous Types or DTOs

LINQ projection shapes each result around the values its caller needs. Learn how Select works with EF Core, when to choose a DTO, and what projection means for tracking and translation.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use LINQ’s Select to shape each result into just the values its caller needs. In EF Core, a translatable projection can also limit the columns requested from the database; in an API, a DTO makes the response shape explicit. Those benefits depend on the query provider and do not make a projected result a tracked entity.

How do I select only the fields I need with LINQ?

Projection transforms each item into a different result form. With in-memory IEnumerable<T>, Select runs as a C# transformation. With IQueryable<T>, such as an EF Core query, the provider receives an expression tree and translates supported parts for its data source. The same-looking expression can therefore have different execution behavior depending on its source. Microsoft’s LINQ documentation describes Select as projection and distinguishes it from SelectMany, which projects sequences and flattens them.

As an Amazon Associate I earn from qualifying purchases.

var urls = blogs.Select(blog => blog.Url);

var cards = blogs.Select(blog => new
{
    blog.BlogId,
    blog.Name,
    blog.Url
});

The first query returns one value per source item. The second constructs a smaller result shape containing three properties. Query syntax uses select for the same operation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
var urls = from blog in blogs
           select blog.Url;

Projection can also happen after filtering and ordering. Keep those operations on the queryable source so the provider can translate them when supported:

var urls = db.Blogs
    .Where(blog => blog.Rating >= minimumRating)
    .OrderBy(blog => blog.Name)
    .Select(blog => blog.Url);

When should I use an anonymous type or a DTO?

Choice Best fit Boundary
Anonymous type A local result shape used within the current method or expression. The compiler generates the type, so source code cannot name it in a method signature or field declaration. Its properties are public and read-only. Microsoft’s C# documentation explains these limits.
Named DTO An API response, a result passed across method boundaries, or a shape that should have a stable explicit name. Define properties for the values the consumer actually needs. ASP.NET Core’s tutorial describes DTOs for hiding properties, flattening graphs, reducing payload fields, and helping prevent over-posting. ASP.NET Core Minimal API tutorial

For a named result, define a DTO and project directly into it:

public sealed record BlogCardDto(int Id, string Name, string Url);

var cards = await db.Blogs
    .Where(blog => blog.Rating >= minimumRating)
    .OrderBy(blog => blog.Name)
    .Select(blog => new BlogCardDto(blog.BlogId, blog.Name, blog.Url))
    .ToListAsync();

This is a pattern, not a guarantee about a particular SQL statement. The generated query depends on the EF Core version, provider, and expression. Inspect the SQL when the columns retrieved or server translation matters.

How can I return a DTO from an EF Core query?

Apply Select before materializing the results, and construct the DTO using the required properties. EF Core’s efficient-querying guidance shows why this matters: selecting an entity can retrieve its full set of mapped columns, while projecting a single property can produce a query that selects only that column. EF Core: Efficient Querying

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Explicit projection can also avoid carrying large columns that the result does not need. In joined queries, repeated large columns can make result sets heavier; the EF Core single-versus-split-query guidance discusses this duplication and projection as a way to omit unnecessary columns. EF Core: Single vs. Split Queries

Why is EF Core fetching every column?

A query that materializes an entity asks EF Core for that entity, not just the properties the calling code later reads. For a read-only result that needs only a few values, project those values instead:

var urls = await db.Blogs
    .Where(blog => blog.Rating >= minimumRating)
    .Select(blog => blog.Url)
    .ToListAsync();

For several values, return an anonymous type for local use or a DTO when the result needs a declared name. Confirm the actual SQL for the query and provider rather than assuming every expression produces a narrow selection.

Does projection keep private fields out of an API response?

A DTO lets the application define which properties appear in a particular response. If a model contains a Secret value that a client must not receive, a response DTO that does not include it keeps that property out of that response’s shape. A different, authorized administrative response may have a different DTO. ASP.NET Core’s tutorial demonstrates DTOs for controlling returned properties and addressing over-posting. ASP.NET Core Minimal API tutorial

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Projection implements the response shape; it does not decide who is authorized to receive each value. The application still needs an authorization policy appropriate to the caller and data.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Will a projected result be tracked for updates?

Do not treat a DTO or anonymous result as if it were the entity loaded for editing. EF Core’s efficient-querying guidance recommends projection particularly for read-only queries, and its query documentation notes that an anonymous projection is not tracked as the underlying entity. Efficient Querying · Single vs. Split Queries

If a workflow must change and save an entity, query the entity in a tracking workflow or deliberately attach and update an entity with the required state. Keep that persistence decision separate from the DTO used to shape an API response.

Which parts of a projection run on the database?

EF Core attempts to evaluate queries on the server. Its documented behavior permits client evaluation in the top-level projection, but an expression that cannot be translated in other parts of the query results in a runtime exception. If a helper in the final projection runs on the client, EF Core may still need to fetch the data required to call it; arbitrary C# methods do not automatically become SQL. EF Core: Client vs. Server Evaluation

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Prefer provider-translatable expressions for filtering, ordering, and limiting results.
  • Keep client-only formatting or calculations in the final projection when appropriate, and check what source values that work requires.
  • Inspect generated SQL when column selection, query execution location, or performance is important.
  • Check behavior against the EF Core version and database provider used by the application.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.