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

如何将FormCollection处理得到的泛型匿名列表转换为Dictionary或List?

FormCollection数据转换为Dictionary的问题与解决

问题场景

我有一个接收FormCollection的方法,需要将相关数据列表传递至应用层。当前已实现的可行代码如下:

var formIndexes = form.AllKeys.Select((e, i) => new { Name = e, Index = i }).Where(o => o.Name.Contains("StatusId")).ToList();
var formValues = formIndexes.Select(e => new { Value = form[e.Index], Name = e.Name }).ToList();

但formValues是匿名类型的List,当尝试将其转换为Dictionary<string, string>时,出现如下错误:

cannot convert from 'System.Collections.Generic.List<<anonymous type: string Value, string Name>>' to 'System.Collections.Generic.Dictionary<string, string>'

解决方法

参考@DanielA.White的方案,使用ToDictionary方法直接完成转换,代码如下:

formIndexes.Select(e => new { Value = form[e.Index], Name = e.Name }).ToDictionary(a => a.Name, b => b.Value);

内容的提问来源于stack exchange,提问作者Eloa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 16:15:28