2014-01-21 88 views
0

我有字典的名單,我想綁定到C#的winform網格視圖綁定字典的GridView

public class Person { 
    Dictionary<string, object> attributes = new Dictionary<string, object>(); 
    public Dictionary<string, object> Attributes { 
    get { return attributes; } 
    } 
} 

List<Person> persons = new List<Person>(); 
Person person1 = new Person(); 
person1.Attributes.Add("name", "Ross"); 
person1.Attributes.Add("address", "Street 1"); 
persons.Add(person1); 
Person person2 = new Person(); 
person2.Attributes.Add("name", "Tom"); 
person2.Attributes.Add("address", "Street 2"); 
persons.Add(person2); 

所以我如何使用這本詞典將其綁定到網格視圖。它像下面一樣嗎?

GridView1.DataSource = persons.Select(x => x.Attributes).ToList(); 

我要的是網格以顯示字符串(鍵)是列
例如
名稱|地址
Ross | Street 1
Tom | Street 2

可能嗎?

回答

0
GridView1.DataSource = 
persons.Select(p => new 
{name = p.Attributes["name"], address = p.Attributes["address"]}); 
+0

我覺得匿名類型是要走的路,但你需要添加.ToList()來強制查詢執行.. – TDull

0

試試這個

List<Person> persons = new List<Person>(); 
      Person person1 = new Person(); 
      person1.Attributes.Add("name", "Ross"); 
      person1.Attributes.Add("address", "Street 1"); 
      persons.Add(person1); 
      Person person2 = new Person(); 
      person2.Attributes.Add("name", "Tom"); 
      person2.Attributes.Add("address", "Street 2"); 
      persons.Add(person2); 

      List<KeyValuePair<string, string>> items = persons.Select(person => new KeyValuePair<string, string>(person.Attributes["name"].ToString(), person.Attributes["address"].ToString())).ToList(); 

      dataGridView1.DataSource = items;