0

我正在使用具有两列文本数据的数据表,我只想为每一行扩展缩写,所以我使用了 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;
     }

它可以毫无例外地运行,但它不起作用

4

2 回答 2

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);
于 2013-03-13T10:22:47.017 回答
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);

DataBind()如果您最后使用 Web 表单,您也会错过

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

mz

于 2013-03-13T10:29:10.300 回答