2011-04-19 55 views
5

我有下面的代碼片段到C#列表使用LINQ

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

嗯,我_was_要發佈,但不知何故,我覺得喬恩斯基特將有一個更好的解決方案。 ; p – 2011-04-19 15:29:56

+0

當然可以這樣做,但是如果你能告訴我們爲什麼數據已經這樣結束了,它會有所幫助。例如,你爲什麼要壓扁字典列表?這隻會讓它更難。 – Ani 2011-04-19 15:31:26

+0

@Ani:我錯誤地粘貼了該代碼。我的要求是隱藏列表到類型列表 – 2011-04-19 16:00:07

回答

13

好創建從結果查詢列表列出 ,你可以這樣做:

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

這是你在想什麼嗎?你可以通過遍歷字典和使用反射設置屬性來使它更通用......但是,當然,它會變成明顯更長的代碼。

+2

該死的你擊敗了我到它需要點擊提交! – 2011-04-19 15:31:53

+1

感謝您的回答。 – 2011-04-19 15:37:08

2

試試這個

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

}).ToList();