.NET过滤类中列表遇类型转换错误,求快速解决方法
类型转换错误快速修复
定义的类模型
public record AllTransactionsResponse { public List<TransactionItem> Item { get; init; } } public record TransactionItem { public string FundCode { get; init; } public FundTransactionResponse IssuanceItem { get; init; } public FundRedemptionTransactionResponse RedemptionItem { get; init; } }
问题代码与报错
错误代码
var allTransactions = new AllTransactionsResponse(); allTransactions = allTransactions.Item.Where(i => i.FundCode!="11277").ToList();
报错信息
Cannot implicitly convert type 'System.Collections.Generic.List<easy.fund.api.Application.Queries.TransactionItem>' to 'easy.fund.api.Application.Queries.AllTransactionsResponse'
最快解决方法
方法1:创建新的响应实例(推荐,符合record不可变设计)
由于AllTransactionsResponse的Item属性是init修饰(仅初始化阶段可赋值),直接创建新实例并传入过滤后的列表即可:
var allTransactions = new AllTransactionsResponse(); // 过滤列表,处理空引用场景 var filteredItems = allTransactions.Item?.Where(i => i.FundCode != "11277").ToList() ?? new List<TransactionItem>(); // 生成新的响应对象 allTransactions = new AllTransactionsResponse { Item = filteredItems };
方法2:修改属性修饰符(适合频繁修改场景)
如果允许调整类模型,将Item的init改为set,即可直接给属性赋值,无需创建新实例:
// 修改类模型 public record AllTransactionsResponse { public List<TransactionItem> Item { get; set; } } // 修改后的业务代码 var allTransactions = new AllTransactionsResponse(); allTransactions.Item = allTransactions.Item.Where(i => i.FundCode != "11277").ToList();
内容的提问来源于stack exchange,提问作者Ehsan Akbar
相关产品推荐
相关产品推荐

