Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of Dictionary to List<Type> using Linq

Tags:

c#

linq

I have following code snippet into 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>

Now I want to create List from the result query using linq

like image 859
santosh singh Avatar asked Apr 19 '11 15:04

santosh singh


2 Answers

Well, you could do something like:

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

Is that what you were thinking of? You could make it more general-purpose by iterating over the dictionary and setting properties with reflection... but it would become significantly longer code, of course.

like image 135
Jon Skeet Avatar answered Nov 16 '22 05:11

Jon Skeet


try this

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

}).ToList();
like image 24
Maged Samaan Avatar answered Nov 16 '22 04:11

Maged Samaan