对数据表的LINQ查询返回错误的结果
本文关键字:错误 结果 返回 LINQ 数据表 查询 | 更新日期: 2023-09-27 18:06:00
我想LINQ查询到Datatable,以便选择具有特定ID的名称,但它返回名称的长度而不是字符串,这里是一些示例代码:
private void btnShow(object sender, EventArgs e)
{
DataTable CL = new DataTable();
DataRow rt;
CL.Columns.Add(new System.Data.DataColumn("ID", typeof(string)));
CL.Columns.Add(new System.Data.DataColumn("Name", typeof(string)));
for (int i = 0; i< dataGridView1.Rows.Count; i++)
{
rt = CL.NewRow();
rt[0] = dataGridView1.Rows[i].Cells[0].Value.ToString();
rt[1] = dataGridView1.Rows[i].Cells[1].Value.ToString();
CL.Rows.Add(rt);
}
var results = from myRow in CL.AsEnumerable()
where myRow.Field<string>("ID") == "1"
select myRow.Field<string>("Name").ToString();
dataGridView2.DataSource = results.ToList();
}
提前致谢
我怀疑Value
正在返回您没有怀疑的值。
首先,试试:
for (int i = 0; i< dataGridView1.Rows.Count; i++)
{
rt = CL.NewRow();
string value1 = dataGridView1.Rows[i].Cells[0].Value;
string value2 = dataGridView1.Rows[i].Cells[1].Value.ToString();
//Breakpoint here, check the values of value1 and value2
CL.Rows.Add(rt);
}
我也会尝试你的查询的不同变体。
string[] names = dt.Rows.Cast<DataRow>().Where(row => row["Id"] == 1).Select(row => row["Name"].ToString()).ToArray();
此时检查名称。
private void btnShow(object sender, EventArgs e)
{
DataTable CL = new DataTable();
DataRow rt;
DataTable dt = new DataTable();
DataRow row;
CL.Columns.Add(new System.Data.DataColumn("ID", typeof(string)));
CL.Columns.Add(new System.Data.DataColumn("Name", typeof(string)));
for (int i = 0; i< dataGridView1.Rows.Count; i++)
{
rt = CL.NewRow();
rt[0] = dataGridView1.Rows[i].Cells[0].Value.ToString();
rt[1] = dataGridView1.Rows[i].Cells[1].Value.ToString();
CL.Rows.Add(rt);
}
IEnumerable<DataRow> results = from myRow in CL.AsEnumerable()
where myRow.Field<string>("ID") == "1"
select myRow;
foreach (var re in results)
{
row = dt.NewRow();
dt.Rows.Add(st.Field<string>("Name"));
}
dataGridView2.DataSource = dt;
}