繁体   English   中英

字典值到数据表C#

[英]Dictionary value to Data table c#

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

上面是我的字典键值对。

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

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

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

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

最初,我尝试使用

  string[] Topic_County = key.Split('~');

因此Topic_County由[0] =种族分配[3] [1] =县名组成

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

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

如果使用这样的简单类:

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);
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM