Transform a List of objects to a string of unique values for use in an SQL query
Creating query (alternative)

Creating SQL like that is vulnerable to SQL Injection. You should use parameters instead.

Here's an example:

using (var cmd = new SqlCommand())
{
    var methods = results
        .SelectMany(x =&gt; x.Method?.Split(
            new[] { ':' }, 
            StringSplitOptions.RemoveEmptyEntries) ?? new string[0]
        ).Distinct();

    var methodParameterNames = new List&lt;string&gt;();
    foreach (var method in methods)
    {
        methodParameterNames.Add($"@Method{methodParameterNames.Count + 1}");
        cmd.Parameters.Add($"@Method{methodParameterNames.Count}", SqlDbType.NVarChar).Value = result;
    }
    var methodParameterString = string.Join(", ", methodParameterNames);

    // build the rest of the query
}




Extracting methods

To extract all methods use the SelectMany extension with the coalescing operator ?? so that you don't have to check for null later. You use an empty collection. The loop simply won't execute. Finally you get unique methods with Distinct.

Creating SQLParameters

In order to create a query for each result you create a SqlCommand. You add each method to a list with parameter names and at the same time add the parameters and the values to the command. The parameters have counters. The first counter needs to be +1 because it is just going to be added and it has to match the counter in the parameter line. At the end you build a string with parameter names that you can use to build the final query.

Example methodParameterString:


 @Method1, @Method2, @Method3



The query to create:

 var sql = $".. WHERE [Method] IN ({methodParameterString}) ..";




Review


string.Join(",", [...].ToArray());



There's no need to .ToArray() the collection for string.Join because it expects an IEnumerable&lt;T&gt;. Calling ToArray you loop over the collection twice.




const string separator = ":";
separator[0]



You can make the separator a char and drop the [0] which is very confusing.




.Where(x =&gt; x.Method?.Length &gt; 0)



It's easier to do:

.Where(x =&gt; !string.IsNullOrEmpty(x.Method))