我正在尝试获取所有汽车的总和。但是我只是得到每个项目的总和,您可以在这里看到链接
那么,如何才能获得所有项目的总和,而不是获得每个项目,就像总和是(4)一样?
控制器:
public ActionResult Home()
{
var model = new CompositeModel();
model.CountCars = getCountOfCars();
return View(model);
}
private IEnumerable<CountCarsrCountView> getCountOfCars()
{
var countCars = this.Data.Cars.All()
.Select(t => new CountCarsrCountView
{
counter = t.Cars.Count()
});
return countCars ;
}
视图模型
public class CountCarsViewModel
{
public int counter { get; set; }
}
复合模型
public class CompositeModel
{
public IEnumerable<CountCarsViewModel> CountCars { get; set; }
}
看法
@model CompositeModel
<div class="container">
@for (int i = 0; i < Model.CountCarsViewModel.Count(); i++)
{
var cars = Model.CountCarsViewModel.ElementAt(i);
<p>@cars.counter</p>
}
</div>
汽车模型:
public class Car
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Price { get; set; }
public virtual Category Category { get; set; }
public int CategoryId { get; set; }
public int FilePathId { get; set; }
public string FileName { get; set; }
public string UserId { get; set; }
public virtual User Users { get; set; }
}
您可以这样使用Linq:
public class MyItem
{
public int MyCount { get; set; }
}
public List<MyItem> AllItems { get; set; }
在此示例中,如果您希望对列表中的所有项目进行计数,则可以执行以下操作:
var count = AllItems.Count();
如果要汇总列表中所有项目的计数,请执行以下操作:
var count2 = AllItems.Sum(a => a.MyCount);
例子:
AllItems = new List<UserQuery.MyItem>()
{
new MyItem(){ MyCount = 3 },
new MyItem(){ MyCount = 4 },
};
var count = AllItems.Count(); // This would be 2
var count2 = AllItems.Sum(a => a.MyCount); // This would be 7
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句