我试图获得所有汽车项目的总和。但我只是得到每个项目的总和,你可以在这里看到Link
那么如何得到所有项目的总和,比如总和是(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; }
}
CompositeModel
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; }
}
答案 0 :(得分:1)
您可以使用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