簡體   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