【问题标题】:Binding List of KeyValuePairs in DataGrid, each key is coulmn headerDataGrid中键值对的绑定列表,每个键为列标题
【发布时间】:2018-11-23 14:55:08
【问题描述】:

我有一个带有指定参数(字符串/整数)和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 键在 API 中是静态的,与类别不同。一次我只能有一个键列表。 我不知道如何绑定它。

【问题讨论】:

标签: c# wpf binding datagrid keyvaluepair


【解决方案1】:

您需要一个数据透视表。下面的代码创建了一个 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; }
    }
}

【讨论】:

  • 使用 SelectMany 作为第一种方法会不会更短:products.SelectMany(x =&gt; x.AttributeList.Select(y =&gt; y.Key)).Distinct()
  • @ASh :是的,你是对的。我只是习惯将 SelectMany 放在查询的末尾。通常我使用 GroupBy 然后 SelectMany。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 2023-03-07
  • 2011-12-25
  • 1970-01-01
相关资源
最近更新 更多