使用 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] 删除。
我来说两句