如何在MyItemViewModel中按ItemGroup赋值派生属性并解决语法错误?
问题解决与正确实现方案
错误原因分析
"Block bodies and expression bodies cannot both be provided" 错误
你同时混用了属性的表达式体(=>)和块体({})写法,比如错误代码:// 错误示例:同时使用=>和{} public decimal SteelWeight => { return Items.First(...).Weight; }C#不允许属性同时采用这两种语法,必须二选一。
decimal类型无法调用Where的问题
Where是Linq集合方法,仅适用于IEnumerable<T>类型,你错误地对单个decimal值(比如某条数据的Weight字段)调用了Where,而非对Items集合使用该方法筛选数据。
正确实现代码
假设你的基础类结构如下:
// 存储过程返回的单条数据模型 public class MyItem { public string ItemGroup { get; set; } public decimal Weight { get; set; } public decimal Price { get; set; } } // 视图模型,已填充Items列表 public class MyViewModel { public List<MyItem> Items { get; set; } = new List<MyItem>(); // 表达式体写法:获取Steel组的Weight(假设每组仅一条数据) public decimal SteelWeight => Items.FirstOrDefault(i => i.ItemGroup == "Steel")?.Weight ?? 0; // 表达式体写法:获取Steel组的Price public decimal SteelPrice => Items.FirstOrDefault(i => i.ItemGroup == "Steel")?.Price ?? 0; // 若每组有多条数据,需求和的场景(表达式体写法) public decimal TotalSteelWeight => Items.Where(i => i.ItemGroup == "Steel").Sum(i => i.Weight); // 块体写法:适合需要复杂逻辑的场景 public decimal TotalSteelPrice { get { var steelItems = Items.Where(i => i.ItemGroup == "Steel"); return steelItems.Any() ? steelItems.Sum(i => i.Price) : 0; } } }
模板使用说明
这些派生属性可直接在HTML模板中用于属性替换,比如在Razor模板中:
<div> Steel重量:@Model.SteelWeight<br> Steel总价:@Model.TotalSteelPrice </div>
内容的提问来源于stack exchange,提问作者Jesus
相关产品推荐
相关产品推荐

