简体   繁体   English

计算我的ASP.NET MVC项目中相同产品名称的总和

[英]Count total sum of the same product name in my ASP.NET MVC Project

How do I count total amount of cars of the same car name by a group using LINQ (using Query or method syntax)..? 如何使用LINQ(使用查询或方法语法)计算同一车辆名称的汽车总数。 My table name "Cars" looks like following: 我的表名“Cars”如下所示:

CarId   CarName Color   Status
1      Volvo    Red      2 
2      Toyota   Black    1
3      Volvo    White    5
4      Ford     Blue     3
5      Toyota   Silver   5

I want result like this (Name of the Car and summery of Status): 我想要这样的结果(汽车名称和状态总结):

Volvo   7
Toyota  6
Ford    3

In this Result I have 7 Volovs, 6 Toyotas and 3 Fords. 在这个结果中,我有7个Volov,6个丰田和3个福特。
How should I form it to get the correct Result that I'am looking for? 我应该如何形成它以获得我正在寻找的正确结果? I tried 我试过了

 [HttpGet]
        public async Task<ActionResult> GetSumOfCars()
        {
            using (context)
            {
                return (PartialView("_CarList", await context.Cars.GroupBy(m =>m.CarName).Count????.ToListAsync()));
            }

        }

or LINQ (using query syntax) 或LINQ(使用查询语法)

var _Results = from Cars in ???
        Count(Status)
                groupedby CarName
                select Status;

But givs me wrong Result. 但是给我错误的结果。 I would be grateful if you guys would help me. 如果你们能帮助我,我将不胜感激。

The group by section of your query is correct. 您的查询的分组是正确的。

Selecting count from the group usually comes with an anonymous class: 从组中选择计数通常带有一个匿名类:

return PartialView(
    "_CarList",
    await context.Cars
        .GroupBy(m =>m.CarName)
        .Select(g => new { CarName = g.Key, Count = g.Sum(c => c.Status) })
        .ToListAsync()
);
from car in context.Cars 
group car by new { car.CarName } into carGrouping
select new {
  Name=carGrouping.Key,
  Count = carGrouping.Count()
};

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

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