【问题标题】:Dictionary value to Data table c#字典值到数据表c#
【发布时间】:2013-11-15 12:20:40
【问题描述】:
Allocation of Race[3]~Brown County,Total:~6866,Allocated~315,Not allocated~6551
Allocation of Age[3]~Brown County,Total:~6866,Allocated~315,Not allocated~6551
Allocation of Race[3]~Boone County,Total:~6866,Allocated~315,Not allocated~6551
Allocation of Age[3]~Boone County,Total:~6866,Allocated~315,Not allocated~6551

上面是我的字典键值对。

Key = 种族分配[3]~布朗县 && 值=总计:~6866,已分配~315,未分配~6551

我正在尝试将这些值插入数据表中

  table.Columns.Add("Topic");
  table.Columns.Add("County");
  table.Columns.Add("Header");
  table.Columns.Add("Value");

在我的键值对中,topic = 种族分配[3] && 县 = 布朗县 && 标头 = 总计、已分配和未分配,值 = 它们各自的值。

最初,我尝试使用

拆分密钥对
  string[] Topic_County = key.Split('~');

所以 Topic_County 由 [0] = 种族分配[3] [1]= 县名

  foreach (string tc in Topic_County)
            {
                table.Rows.Add(tc);    
            }

当我使用 foreach 循环时,种族和县名的分配出现在同一列中 如何在县列下添加县名,以及相应位置的标题和值。

【问题讨论】:

  • 考虑重新设计你的数据结构
  • 您能否建议我在网页上显示字典元素的最佳方式
  • 您似乎在使用Dictionary<string,string> 尝试将其更改为Dictionary<SomeStruct,SomeClass>。某些结构将是不可变类型。 SomeClass 将具有 Total、已分配和未分配的属性。您需要使用IEqualityComparer<TKey> 来比较您的结构。

标签: c# dictionary datatable


【解决方案1】:

如果你使用这样的简单类:

public class Datum
{
    public string Topic = "";
    public string County = "";
    public int Allocated = 0;
    public int NotAllocated = 0;

    public int Total()
    {
        return Allocated + NotAllocated;
    }
}

您仍然可以使用字典,只需使用 Topic 属性和 County 属性作为键:

        Dictionary<string, Datum> MyData = new Dictionary<string, Datum>();
        Datum info = new Datum
        {
            Topic = "Allocation of Race[3]",
            County = "Brown County",
            Allocated = 315,
            NotAllocated = 6551
        };
        MyData.Add(info.Topic + "-" + info.County, info);

虽然列表可能也能正常工作,但使用 LINQ,您可以提取任何需要按您设置的标准进行分组或排序的项目。

由于 Total 是一种方法,因此您无需将其添加到字典中,只需在需要值时将其作为 Datum 的成员调用即可。

您可以像这样将数据添加到数据表中:

        DataTable table = new DataTable();
        table.Columns.Add("Topic");
        table.Columns.Add("County");
        table.Columns.Add("Allocated");
        table.Columns.Add("Not Allocated");
        table.Columns.Add("Total");
        foreach(Datum entry in MyData.Values)
        {
            DataRow NewDataRow = table.NewRow();
            NewDataRow.ItemArray = new string[5]
            {
                entry.Topic,
                entry.County,
                entry.Allocated.ToString(),
                entry.NotAllocated.ToString(),
                entry.Total().ToString()
            };
            table.Rows.Add(NewDataRow);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多