将 List<IDictionary<string, string>> 转换为 C# 中的强类型列表

罗伯特·史密斯

使用 C#,我有以下使用 IDictionary 的列表:

List<IDictionary<string, string>> lstDictionary;

填充上面的列表后,我需要将其转换为基于类的强类型列表:

public class customer
    {
        public string FirstName{ get; set; }
        public string LastName{ get; set; }
        public string Status{ get; set; }
    }
List<customer> lstCustomers;

所以现在,我正在尝试使用 LAMBDA/LINQ 进行转换但无法正常工作(在 p.FirstName 上显示错误消息):

lstCustomers = lstDictionary.Select(p => new customer
            {
                FirstName = p.FirstName,
                LastName = p.LastName,
                Status = p.Status
            }).ToList();

任何帮助,将不胜感激。

乔尔·科霍恩

请记住,p调用 to中的每个Select都是一个IDictionary<string, string>. 在 .Net 中,您使用索引器来访问字典中的元素;没有p.FirstName,但可能有p["FirstName"]

因此,假设密钥始终正确设置,它将如下所示:

lstCustomers = lstDictionary.Select(p => new customer
        {
            FirstName = p["FirstName"],
            LastName = p["LastName"],
            Status = p["Status"]
        }).ToList();

最后,我需要在我的第一段中指出“可能”。如果 Dictionary 以意外数据结束,这有可能在运行时崩溃。在 .Net 世界中,这被认为是糟糕的设计,通常是早期犯错的结果。有时候,无论如何你已经走得够远了,但错误仍然存​​在。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

C#将List <string>转换为Dictionary <string,string>

将IDictionary <Guid,string>转换为IEnumerable <SelectListItem>

将 List<List<String>> 转换为 String[][]

如何将词典列表转换为IDictionary“ C#”

如何使用键作为标题将C#中的字典<string,List <string >>转换为csv?

将类型为List <object>的对象转换为List <string>

Powershell将String []转换为List <String>

将C#List <string>转换为Javascript

如何将DriveInfo []转换为List <string> C#

将Dictionary <string,List>的列表转换为列表C#Linq

将CType转换为C#时,无法将类型'string'隐式转换为'string []'

使用 Java 8 中的列表值将 List<String> 转换为 Map<String, String>

将List <Integer>转换为List <String>

将List <dynamic>转换为List <string>

将 List<List<String>> 转换为 csv

将List <T>转换为List <string>

将Entry <String,List <String >>转换为Entry <String,String>

将HashMap <String,String>转换为HashMap <String,List <String >>()

将List <Map <String,List <String >>>转换为String [] []

将IEnumerable <foo>的列表转换为List <string>

将ListBox中的字符串转换为List <String>

如何将Hashmap中的值转换为List <String>

将 List<List<TextValue>> 转换为 List<Map<String, String>>

在ASP.NET MVC 4中将列表<List <KeyValuePair <string,string >>>转换为json?

Java:将List <Integer>转换为String

将枚举转换为List <string>

将Collection <Object>转换为List <String>

将String []转换为List <SelectList>

将List <string>转换为流