Leonardo Daga
Leonardo Daga

Reputation: 145

Where, Select and Single in Linq: What is the most efficient use with ASP.NET Core?

As far as I know, there is not a way to select information from the output of a Single statement. It means it is not possible to write like this:

var playerIdName = context.Players
    .Single(p => p.ID == playerID)
    .Select(p => new 
    {
        ID = p.ID,
        Name = p.Name + " " + p.LastName,
    });

Instead, you can write in this two ways:

var playerIdName = context.Players        
    .Select(p => new 
    {
        ID = p.ID,
        Name = p.Name + " " + p.LastName,
    })
    .Single(p => p.ID == playerID);

or

var playerIdName = context.Players
    .Where(p => p.ID == playerID)
    .Select(p => new 
    {
        ID = p.ID,
        Name = p.Name + " " + p.LastName,
    }).Single(p => p.ID == playerID);

but both of them seem tremendously unefficient. Any suggestion of what is the efficiency of this two statements and what is the better way to get information from a selected item apart to make two different statements like:

var player = context.Players
    .Single(p => p.ID == playerID);
var playerIdName = new 
    {
        ID = player .ID,
        Name = player .Name + " " + player .LastName,
    };

Upvotes: 0

Views: 121

Answers (1)

juunas
juunas

Reputation: 58733

How about:

var playerIdName = context.Players
    .Where(p => p.ID == playerID)
    .Take(1)
    .Select(p => new 
    {
        ID = p.ID,
        Name = p.Name + " " + p.LastName,
    })
    .Single();

Take(1) will get the first object that matches the filter in the Where(), Select() projects it, and Single() then executes the whole set. The iterator in Where() will only iterate until it finds the first match.

I did not test if EF is able to convert this to SQL.

Upvotes: 1

Related Questions