Tell me how to do it right. There is a list with an indefinite number of entries:

List<string> Sample= new List<string>(); 

How to run this list through SQL query for each value individually, for example:

 SELECT * FROM db WHERE c1 = "значение из LIST" 
  • if c1 is an integer then you need to form something like this: SELECT * FROM db WHERE c1 in (1,3,5) and the list can be formed like this: List<string> Sample = new List<string>() { "1", "3", "5" }; var result = String.Join(", ", names.ToArray()); List<string> Sample = new List<string>() { "1", "3", "5" }; var result = String.Join(", ", names.ToArray()); - virex-84
  • @ virex-84, not exactly what I need, IN implies that the entire list will be loaded into the SQL query. I also need that for each line from the List, the information was selected separately. - Andrey Zhuravlev
  • then you need to cycle through all the elements of the list, and execute the request for each element, or generate a list of requests and later execute them somewhere - virex-84
  • @ virex-84, the actual question is this. How to arrange a cycle correctly) - Andrey Zhuravlev
  • one
    at least for, at least foreach foreach(String item in Sample) { } for(int i = 0; i < Sample.Count; i++) { } - virex-84

2 answers 2

Let me show you a complete example.

First, you always need to use parameters. This will protect against sql injections and speed up the execution of queries.
Secondly, it is always necessary to release the occupied resources, therefore we use the using construction.
Thirdly, we observe the generally accepted naming.

It is given: the filled list

 List<string> samples = new List<string>(); 

Code:

 using (var conn = new SqlConnection(connectionString)) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT * FROM table WHERE c1 = @param"; ; var sqlParameter = cmd.Parameters.Add("param", SqlDbType.NVarChar); foreach (var sample in samples) { sqlParameter.Value = sample; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { // здесь получаем значения из ридера } } } } } 

You did not specify which DBMS you are using. The example assumes Sql Server. If another is used, replace, respectively, SqlConnection and SqlDbType with the desired types.

    Choose any of the options:

    one.

     List<string> strings = new List<string> {"a", "b", "asdf"}; //в даном случае это генерация листа, но можно и достать готовый из БД. strings.ForEach(a=> Console.WriteLine(a)); //вывод в консоль каждого из элементов 

    2

     foreach(string item in strings) { Console.WriteLine(item); } 

    3

     for(int i = 0; i < strings.Count; i++) { Console.WriteLine(strings[i]); } 
    1. If I need T-SQL specifically, then I will not tell you, but this is easily googled by the query "transact sql foreach"
    • Everything is good, but correct one thing: ForEach is not Linq , this is the standard method List<T> ) - Kir_Antipov February