如何将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
相关产品推荐
相关产品推荐

