Click here to Skip to main content
15,883,787 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
For Example I have an array,


C#
string[] ClassEightstudents= ctx_School.Students.Where(x => x.StudentClass== "8").Select(x => x.StudentName).ToArray();


Now I want to pass this in query C#,

C#
cmd.CommandText=select * from CricketTable where studentname in '"+ClassEightstudents+"'
Posted
Updated 12-Oct-15 20:59pm
v2

Refer: Parameterize an SQL IN clause[^]

You can parameterize each value, so something like:

C#
string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
string cmdText = "select * from CricketTable where studentname IN ({0})";

string[] paramNames = tags.Select(
    (s, i) => "@tag" + i.ToString()
).ToArray();

string inClause = string.Join(",", paramNames);
using (SqlCommand cmd = new SqlCommand(string.Format(cmdText, inClause))) {
    for(int i = 0; i < paramNames.Length; i++) {
       cmd.Parameters.AddWithValue(paramNames[i], tags[i]);
    }
}


Which will give you:

C#
cmd.CommandText = "select * from CricketTable where studentname IN (@tag0,@tag1,@tag2,@tag3)"
cmd.Parameters["@tag0"] = "ruby"
cmd.Parameters["@tag1"] = "rails"
cmd.Parameters["@tag2"] = "scruffy"
cmd.Parameters["@tag3"] = "rubyonrails"
 
Share this answer
 
v2
Comments
Krunal Rohit 13-Oct-15 3:39am    
looks good. 5!

-KR
Palash Mondal_ 13-Oct-15 4:30am    
Thanks :)
You can use

C#
string[] ClassEightstudents= ctx_School.Students.Where(x => x.StudentClass== "8").Select(x => x.StudentName).ToArray();

          string str = "select * from CricketTable where studentname in ('" + String.Join("','", ClassEightstudents) + "')";
 
Share this answer
 
Comments
Krunal Rohit 13-Oct-15 3:39am    
looks good. 5!

-KR
[no name] 13-Oct-15 3:47am    
Thanks Krunal ..
shaprpuff 13-Oct-15 4:25am    
I like your solution is much better.
[no name] 13-Oct-15 4:54am    
Thanks Shaprpuff.
i did this solution and its work for me.
C#
string[] ClassEightstudents= ctx_School.Students.Where(x => x.StudentClass== "8").Select(x => x.StudentName).ToArray();

foreach (var item in ClassEightstudents)
  {
      ClassEightstudentsformat =ClassEightstudentsformat+ "'" + item + "'" + ",";
  }
   ClassEightstudentsformat =ClassEightstudentsformat .TrimEnd(',');


then pass it into command

C#
cmd.CommandText=select * from CricketTable where studentname in '"+ClassEightstudentsformat +"'
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900