如何逐行扩展数据表中的缩写c#

时间:2013-03-13 10:13:07

标签: c# dictionary datatable abbreviation

我正在使用有两列文本数据的数据表,我只想为每一行扩展缩写,所以我使用了Dictionary,这里是我的代码示例:

   private void ExpandWords()
    {    
        DataTable DT = new DataTable();
        DataRow Row;
        DT.Columns.Add(new System.Data.DataColumn("Name", typeof(string)));
        DT.Columns.Add(new System.Data.DataColumn("Label", typeof(string)));

        Dictionary<string, string> dict = new Dictionary<string, string>();
        dict.Add("emp", "employee");
        dict.Add("dep", "department");

        for (int i = 0; i < dataGridView6.Rows.Count; i++)
        {   
            Row = DT.NewRow();
            foreach(KeyValuePair<string,string> rep in dict)
            {
              Row[0] = dataGridView6.Rows[i].Cells[0].Value.ToString().Replace    (rep.Key, rep.Value);
              Row[1] = dataGridView6.Rows[i].Cells[1].Value.ToString().Replace  (rep.Key, rep.Value);
            }
        DT.Rows.Add(Row);
        dataGridView7.DataSource = DT;
     }

它可以无异常地运行但不起作用

2 个答案:

答案 0 :(得分:0)

为什么要在网格行的循环中枚举字典?只需查找密钥即可。

您还必须在循环中添加每一行,而不是在外部,否则您只需添加最后一行:

for (int i = 0; i < dataGridView6.Rows.Count; i++)
{   
    Row = DT.NewRow();
    string abbrCell1 = dataGridView6.Rows[i].Cells[0].Value.ToString();
    string abbrCell2 = dataGridView6.Rows[i].Cells[1].Value.ToString();
    Row[0] = dict[abbrCell1];
    Row[1] = dict[abbrCell2];
    DT.Rows.Add(Row);
}

编辑如果要将数据网格单元格的字符串中的所有缩写词替换为字典中未缩写的单词,则可以使用以下代码:

// in the loop
Row = DT.NewRow();
string abbrCell1 = dataGridView6.Rows[i].Cells[0].Value.ToString();
string abbrCell2 = dataGridView6.Rows[i].Cells[1].Value.ToString();
IEnumerable<string> unabbrWords1 = abbrCell1.Split()
    .Select(w => dict.ContainsKey(w) ? dict[w] : w);
IEnumerable<string> unabbrWords2 = abbrCell2.Split()
    .Select(w => dict.ContainsKey(w) ? dict[w] : w);
Row[0] = string.Join(" ", unabbrWords1);
Row[1] = string.Join(" ", unabbrWords2);
DT.Rows.Add(Row);

答案 1 :(得分:0)

您应该稍微更改它,否则您将在循环中覆盖相同的值:

var value1 = dataGridView6.Rows[i].Cells[0].Value.ToString();
var value2 = dataGridView6.Rows[i].Cells[1].Value.ToString();
foreach (KeyValuePair<string, string> rep in dict)
{
    value1 = value1.Replace(rep.Key, rep.Value);
    value2 = value2.Replace(rep.Key, rep.Value);
}

DT.Rows.Add(value1, value2);

如果你最后使用的是Web表单,那么你也会遗漏DataBind()

dataGridView7.DataSource = DT;
dataGridView7.DataBind();

MZ