将 List<IDictionary<string, string>> 转换为 C# 中的强类型列表
Convert List<IDictionary<string, string>> to strongly typed list in C#
使用 C#,我有以下使用 IDictionary 的列表:
List<IDictionary<string, string>> lstDictionary;
填充上面的列表后,我需要将其转换为基于 class:
的强类型列表
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();
如有任何帮助,我们将不胜感激。
请记住,对 Select
的调用中的每个 p
都是一个 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 世界中,这被认为是糟糕的设计,通常是早期错误的结果。有时你已经走得够远了,但错误仍然存在。
使用 C#,我有以下使用 IDictionary 的列表:
List<IDictionary<string, string>> lstDictionary;
填充上面的列表后,我需要将其转换为基于 class:
的强类型列表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();
如有任何帮助,我们将不胜感激。
请记住,对 Select
的调用中的每个 p
都是一个 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 世界中,这被认为是糟糕的设计,通常是早期错误的结果。有时你已经走得够远了,但错误仍然存在。