Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net-core linq

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

发布于 2020-03-27 15:45:14

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,
    };
Questioner
Leonardo Daga
Viewed
72
juunas 2020-01-31 17:02

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.