gpt4 book ai didi

c# - 如何使用 Criteria 打印 List

转载 作者:太空宇宙 更新时间:2023-11-03 17:17:19 27 4
gpt4 key购买 nike

这是我的简单列表:

public class ProductStore
{
public List<Product> AllProducts
{
get
{
return new List<Product>
{
new Product{Name = "Stove 1", Category= "Stoves", ID = 1, Price = 99.99},
new Product{Name = "Stove 2", Category= "Fireplaces", ID = 2, Price = 139.50},
new Product{Name = "Stove 3", Category= "Stoves", ID = 3, Price = 199.99},
new Product{Name = "Stove 4", Category= "Stoves", ID = 4, Price = 29.00},
};
}

}
}

这就是我在 View 中打印这些数据的方式: @模型列表

@{
ViewBag.Title = "AllProducts";
}

<h2>AllProducts</h2>
<ul>
@foreach (var product in Model)
{
<li>Name: @product.Name, Category:@product.Category, Price:@product.Price;</li>
}
</ul>

我的问题是:只打印那些元素的最佳方法是什么,即。类别 == 炉子?我知道我可以在 foreach 中将 if 语句与 continue 结合使用,但我想知道,是否有更聪明的方法来做到这一点?

最佳答案

纯 MVC 实现可能会把它放在 Controller 中,但您可以使用这样的 LINQ 查询来过滤您循环访问的产品列表...

@foreach (var product in Model.AllProducts.Where(p => p.Category == "Stoves").ToList())
{
<li>Name: @product.Name, Category:@product.Category, Price:@product.Price;</li>
}

关于c# - 如何使用 Criteria 打印 List<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19413692/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com