2

我想对 Datatable 进行 LINQ 查询以选择具有特定 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();

     }       

提前谢谢

4

2 回答 2

0
    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;

 }    
于 2013-03-27T14:41:49.017 回答
0

我怀疑这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();

然后在此时检查名称。请评论答案第一部分的结果以查看值是什么。

于 2013-03-27T11:53:39.140 回答