Linq使用方法:将字典列表转换为类型列表

5
我将以下代码片段翻译成中文:

我有以下代码片段写在c#中

public class Client
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}




var liste = new List<Dictionary<string, string>>();
            var dictionary = new Dictionary<string, string>();
            dictionary["Id"] = "111";
            dictionary["Name"] = "XYZ";
            dictionary["Address"] = "Addd";
            liste.Add(dictionary);
            var result = liste.SelectMany(x => x);

            //Code for Converting result into List<Client>

现在我想使用linq从查询结果创建列表。

1
好吧,我本来想发帖的,但是我觉得Jon Skeet会有更好的解决方案。;p - Brad Christie
当然可以做到,但如果您能告诉我们为什么数据会变成这样,那会更有帮助。例如,为什么要将字典列表展平?这只会让事情更加困难。 - Ani
@Ani:我不小心粘贴了那段代码。我的要求是将list<dic>转换为类型列表。 - santosh singh
2个回答

13

你可以尝试像这样做:

var result = liste.Select(map => new Client { ID = map["ID"],
                                              Name = map["Name"],
                                              Address = map["Address"] })
                  .ToList();

这是你想要的吗?你可以通过迭代字典并使用反射设置属性来使其更具通用性...... 但代码长度会显著增加,当然。


2
你太快了,我还没来得及点击提交按钮! - anthonyvd

2

试一下这个

var q = (from dic in liste
select new Client
{
Id = dic["Id"],
Name = dic["Name"],
Address = dic["Address"],

}).ToList();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接