簡體   English   中英

需要一種有效的方法來解決C#中的一個簡單問題

[英]Need an efficient way for a simple problem in c#

我正在使用c#開發Web應用程序。 我正在從數據庫中讀取一些數據到名為dt的數據表中。 示例數據如下所示。

agentName  WeekNumber Score 
John       3          45
John       5          78
John       6          33

我想根據某些條件對上述數據進行一些更改。 因為我想根據此數據繪制圖形。代理名稱始終相同。而周字段是唯一的。 我想使用下面列出的條件制作一個新的數據表。

1-新數據表星期字段必須從1開始。如果數據表中沒有第1周的條目,則可以將數據添加到新數據表中,如下所示

John 1  0

這意味着只給0作為分數。

2-如果從數據庫獲得的數據表中的第二行開始缺少任何星期,則添加該星期的行,分數為-1。 在上面的示例中,第一行之后缺少第4周。因此將其添加到得分為-1的新數據表中

新的數據標簽;下面顯示了用於示例數據的e

agentName WeekNumber Score
John      1          0
John      2          0
John      3          45
John      4         -1
John      5         78
John      6         33

我該如何使用C#高效地做到這一點? 行數會有所不同。 我想用c#來做。 由於某些原因而不使用查詢

在數據庫中有一個表,其中包含一年中每周的默認值。 當選擇您的結果時,請在此表上保留Join;如果缺少其他結果,則使用默認值。

例如

select 
    dt.name, 
    def.week_no, 
    (case dt.value is null then def.value else dt value end) value
from 
    def left join dt on def.week_no = dt.week_no

代碼未經測試,但應從默認表中獲取所有內容,並從存在的dt表中獲取行。 如果dt行不存在,它將采用默認值。

其中dt是具有值的現有表,而def是具有每周默認值的表。

您可以使用以下類並從中建立一個新表。

class AgentsData
{
    public static DataTabe ProcessDataTabe(DataTable dt)
    {
        Dictionary<string, AgentData> data = new Dictionary<string, AgentData>();

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string name = dt.rows[i][0].ToString();
            if (!data.ContainsKey(name))
                data.Add(name, new AgentData);
            int week = Convert.ToInt32(dt.rows[i][1]);
            int score = Convert.ToInt32(dt.rows[i][2]);

            data[name].Add(week, score);
        }

        foreach (vat agentData in data.Values)
            agentData.Process();

        //now build new data table from dictionary and return it
    }   
}

class AgentData
{
    public AgentData(string name)
    {
        Name = name;
        WeekScore = new Dictionary<int,int>();
    }

    public void Add(int weekNumber, int score)
    {
        WeekScore[weekNumber] = score;
    }

    public void Process()
    {
        int min = WeekScore.Keys.Min();
        int max = WeekScore.Keys.Max();

        for (int i = 0; i < min; i++)
            WeekScore.Add(i, 0);

        for (int i = min + 1; i < max; i++)
            if (!WeekScore.ContainsKey(i))
                WeekScore.Add(i, -1);
    }

    public string Name {get; private set;}  
    public Dictionary<int, int> WeekScore { get; private set;}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM