温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Where, Select and Single in Linq: What is the most efficient use with ASP.NET Core?
asp.net-core linq

其他 - 在Linq中的何处,选择和单一:ASP.NET Core最有效的使用是什么?

发布于 2020-03-27 16:08:36

据我所知,还没有一种方法可以从Single语句的输出中选择信息。这意味着不可能这样写:

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

相反,您可以通过以下两种方式编写:

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

要么

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);

但是它们似乎都效率极低。关于这两个语句的效率的任何建议,以及从选定项目中分开获取信息以做出两个不同语句的更好方法是什么,例如:

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

查看更多

查看更多

提问者
Leonardo Daga
被浏览
142
juunas 2020-01-31 17:02

怎么样:

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)将获取第一个与Where()中的过滤器匹配的对象,Select()将其投影,然后Single()然后执行整个集合。Where()中的迭代器将仅进行迭代,直到找到第一个匹配项为止。

我没有测试EF是否能够将其转换为SQL。