简体   繁体   English

在 linq 查询中选择 max 或重写方法链语法

[英]Selecting max in linq query or rewriting to method chain syntax

I managed to turn this SQL query:我设法打开了这个 SQL 查询:

SELECT c.carId, c.Codename, count(c.CarId) as [CarCount],
  FROM [DbEfTesting].[dbo].[Cars] c
  left join Accessories a on c.CarId = a.CarId
  left join CarsPeople cp on cp.CarId = c.CarId
  left join People p on cp.PersonId = p.PersonId
  group by c.CarId, c.Codename

into a LINQ query:进入 LINQ 查询:

var x = from c in _context.Cars
    join a in _context.Accessories on c.CarId equals a.Car.CarId
    join j in _context.CarsPeople on c.CarId equals j.CarId
    join p in _context.People on j.PersonId equals p.PersonId
    group c by new { c.CarId, c.Codename } into g
    select new VMCarAggregate()
    {
        CarId = g.Key.CarId,
        Codename = g.Key.Codename,
        CarCount = g.Count()
    };

But now I'm lost trying to include a max value eg the SQL:但是现在我试图包含一个最大值,例如 SQL,我迷路了:

SELECT c.carId, c.Codename, count(c.CarId) as [CarCount], max(a.AccessoryId) ...

I googled it and found lots of answers for method syntax.我用谷歌搜索,找到了很多方法语法的答案。 If I were using method chain syntax, I know I could do something like this:如果我使用方法链语法,我知道我可以做这样的事情:

_context.Accessories.Max(a => a.AccessoryId);

but I can't figure out how to do the group by in method chain syntax so either:但我无法弄清楚如何在方法链语法中进行group by因此:

How can I convert that query to method syntax?如何将该查询转换为方法语法?

or或者

How can I inject a select on the max a.AccessoryId in the LINQ query format?如何在 LINQ 查询格式中对最大 a.AccessoryId 注入选择?

Try the below code once:尝试一次以下代码:

var x = from c in _context.Cars
                    join a in _context.Accessories equals a.Car.CarId
                    join j in _context.CarsPeople on c.CarId equals j.CarId
                    join p in _context.People on j.PersonId equals p.PersonId
                    group new { c.CarId, c.Codename, a.AccesoryId } by new { c.CarId, c.Codename } into g
                    select new
                    {
                        CarId = g.Key.CarId,
                        Codename = g.Key.Codename,
                        CarCount = g.Count(),
                        MaxAccesory = g.Max(z => z.AccesoryId)
                    };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM