[英]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.