代码之家  ›  专栏  ›  技术社区  ›  Krzysztof Lichwiarz

DataGrid中KeyValuePairs的绑定列表,每个密钥都是coulmn头

  •  0
  • Krzysztof Lichwiarz  · 技术社区  · 7 年前

    我有一个具有指定参数(字符串/整数)和 List<KeyValuePair<string, string>>

     public class Product
        {
            public long Id { get; set; }
            public string Name { get; set; }
            public string ReferenceNumber { get; set; }
            public string Category { get; set; }
            public List<KeyValuePair<string, string>> AttributeList { get; set; }
    }
    

    我想将这个对象绑定到DataGrid,但我想将KVP中的每条记录作为列标题和值。比如:

    AttributeList  = new List<KeyValuePair<string, string>>
    {
       new KeyValuePair{"SIZE", "30"}, new KeyValuePair{"WIDTH", "50"}
    }
    

    AttributeList键在不同于category的API中是静态的。在同一时间,我只能有一个密钥列表。 我不知道该怎么绑。

    1 回复  |  直到 7 年前
        1
  •  0
  •   jdweng    7 年前

    你需要一张透视表。下面的代码创建一个DataTable,该DataTable相当于可以绑定到的excel透视表。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<Product> products = new List<Product>();
    
                List<string> keys = products.Select(x => x.AttributeList.Select(y => y.Key)).SelectMany(x => x).Distinct().ToList();
    
                DataTable pivot = new DataTable();
                pivot.Columns.Add("Id", typeof(long));
                pivot.Columns.Add("Name", typeof(string));
                pivot.Columns.Add("ReferenceNumber", typeof(string));
                pivot.Columns.Add("Category", typeof(string));
                foreach (string key in keys)
                {
                    pivot.Columns.Add(key, typeof(string));
                }
    
                foreach (Product product in products)
                {
                    DataRow row = pivot.Rows.Add();
                    row["Id"] = product.Id;
                    row["Name"] = product.Name;
                    row["ReferenceNumber"] = product.ReferenceNumber;
                    row["Category"] = product.Category;
                    foreach (KeyValuePair<string, string> attr in product.AttributeList)
                    {
                        row[attr.Key] = attr.Value;
                    }
    
                }
    
            }
        }
        public class Product
        {
            public long Id { get; set; }
            public string Name { get; set; }
            public string ReferenceNumber { get; set; }
            public string Category { get; set; }
            public List<KeyValuePair<string, string>> AttributeList { get; set; }
        }
    }
    
    推荐文章