如何在数据表中逐行展开缩写
本文关键字:缩写 逐行 数据表 | 更新日期: 2023-09-27 18:03:35
我使用的是有两列文本数据的datatable,我只是想为每一行做缩写展开,所以我使用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;
}
可以正常运行,但是不能正常运行
为什么在网格行循环中枚举字典?只要查找键。
你还必须在循环中添加每一行,而不是在循环外,否则你只添加最后一行:
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);
你应该稍微改变一下,否则你会在循环中覆盖相同的值:
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 Forms,你也缺少DataBind()
dataGridView7.DataSource = DT;
dataGridView7.DataBind();
mz