You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 03:37:23