对数据表的LINQ查询返回不正确的结果

时间:2013-03-27 11:33:14

标签: c# linq datatable

我想LINQ查询到Datatable以便选择具有特定ID的Name,但它返回Names的长度而不是字符串,这里是一些示例代码:

    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();

     }       
提前

thanx

2 个答案:

答案 0 :(得分: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();

然后检查姓名。请回复答案第一部分的结果,看看值是什么。

答案 1 :(得分: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;

 }    
相关问题