如何在 Linq 查询中编写 GroupJoin Lambda 表达式?

How to write GroupJoin Lambda Expression in Linq query?

这里我有一个 lambda 表达式,它根据最高评分选择最佳笑话。

所以关系看起来像这样:1 个笑话有很多收视率。

选择最佳笑话的 lambda 查询如下。

Joke best = jokes.GroupJoin(context.Ratings,  // DBContext
                            j => j.ID,
                            r => r.JokeID,
                            (j, r) => new {
                                           bestJoke = j,
                                           sum = r.Sum(s => s.Rating1)
                                          })
                 .OrderByDescending(j => j.sum)
                 .First().bestJoke;

我很难将其写入 linq 查询。

到目前为止我已经尝试过了。

    Joke best2 = from j in jokes
                 join r in context.Ratings on j.ID equals r.JokeID
                 group j by j into g
                 select new {
                      bestJoke = j,
                      } ...

谁能帮帮我?非常感谢。

您可以尝试这样的操作:

var best2 = (from joke in jokes
             join rating in context.Ratings 
             on joke.ID equals rating.JokeID
             group item by joke into gr
             orderby gr.Sum(x=>x.Rating) descending
             ).FirstOrDefault();

if(best2!=null)
    bestJoke = best2.Key;

但是,您应该记住,上述查询在编译期间将被转换为以流畅语法编写的等效查询(如第一个)。查询语法是提供给我们的语法糖。

GroupJoin可以用join .. in .. on .. into语法表示:

7.16.2.4 From, let, where, join and orderby clauses

A query expression with a join clause with an into followed by a select clause

from x1 in e1
join x2 in e2 on k1 equals k2 into g
select v

is translated into

( e1 ) . GroupJoin( e2 , x1 => k1 , x2 => k2 , ( x1 , g ) => v )

A query expression with a join clause with an into followed by something other than a select clause

from x1 in e1
join x2 in e2 on k1 equals k2 into g
…

is translated into

from * in ( e1 ) . GroupJoin(
  e2 , x1 => k1 , x2 => k2 , ( x1 , g ) => new { x1 , g })
…

但是如您所见,您不能让它在 GroupJoin 调用中生成 (j, r) => new { bestJoke = j, sum = r.Sum(s => s.Rating1) },因此您必须稍后在单独的表达式中 select 求和。