通过比较List中的数据从sql表中提取数据

时间:2012-02-04 08:58:02

标签: c# asp.net sql

我的IDS列表在我的LIST(C#)中说1,2,4,6我需要做的是从我的表中提取与这些IDS相对应的数据连接

enter image description here

我的LIST代码如下:

string str = "SELECT id1 FROM [Example] WHERE id2 = '1' UNION SELECT id2 FROM Example WHERE id1 = '1'";
            ds = new DataSet(str);
            da = new SqlDataAdapter(str, con);
            da.Fill(ds);
            //GridView1.DataSource = ds;
            //GridView1.DataBind();
            DataTable dtDetails = ds.Tables[0];
            List<int> lst =
                                (from dr in dtDetails.AsEnumerable()
                                 select Convert.ToInt32(dr["id1"])).ToList<int>();

以上代码的作用是检索LIST中的no's 2 3 4 6

我想要做的是检索对应于这些不对的id2吗?

编辑:

 string str = "SELECT id1 FROM [Example] WHERE id2 = '1' UNION SELECT id2 FROM Example WHERE id1 = '1'";
        ds = new DataSet(str);
        da = new SqlDataAdapter(str, con);
        da.Fill(ds);
        DataTable dtDetails = ds.Tables[0];
        List<int> lst =
                            (from dr in dtDetails.AsEnumerable()
                             select Convert.ToInt32(dr["id1"])).ToList<int>();

        foreach (int prime in lst) // Loop through List with foreach
        {

             str1 = " SELECT id2 FROM [Connections] where id2= '"+prime+"'";
            SqlCommand cmd1 = new SqlCommand(str1, con);
            cmd1.ExecuteNonQuery();
            DataSet ds1 = new DataSet();
            SqlDataAdapter da1 = new SqlDataAdapter(str1, con);
            da1.Fill(ds1);
            GridView1.DataSource = ds1;
            GridView1.DataBind();

        }
  

我的gridview没有显示任何内容

2 个答案:

答案 0 :(得分:-1)

您可以使用IN作为选择的一部分。因此发送到SQL Server的select语句可以是:

SELECT * FROM [Connections]其中id1 IN(1,2,4,6)

在psudo代码中,这将是:

string list =“1,2,4,6”; string str1 =“SELECT * FROM [Connections]其中id1 IN(”+ list +“)”;

当然,在您的代码中,您将从ID列表中构建列表

答案 1 :(得分:-1)

尝试!

SELECT id2 FROM示例WHERE id2 IN(SELECT id1 FROM [示例] WHERE id2 ='1'UNION SELECT id2 FROM示例WHERE id1 ='1')