Reputation: 1610
Suppose I have a list of object with a property called Id
, I'm trying to join of this values to create a piece for a query such as:
UNION ALL SELECT 30 UNION ALL SELECT 31 UNION ALL SELECT ...
The problem is that I get: 30 UNION ALL SELECT 31 UNION ALL SELECT
Honestly I can't find a way to get it directly from string.JOIN
, this is my implementation:
string.Join("UNION ALL SELECT ", teams.Skip(1).Select(c => c.Id).ToList());
Upvotes: 1
Views: 952
Reputation: 2836
You can use linq.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class Program
{
public static void Main()
{
var values = new List<int> { 1, 2, 3, 4 };
var str = values
.Select(i => $"UNION ALL SELECT {i} ")
.Aggregate(new StringBuilder(), (sb, a) => sb.Append(a), s => s.ToString());
Console.WriteLine(str);
}
}
Upvotes: 1
Reputation: 22876
string.Concat(teams.Skip(1).Select(c => " UNION ALL SELECT " + c.Id));
or to avoid the leading space :
string.Join(" ", teams.Skip(1).Select(c => "UNION ALL SELECT " + c.Id));
Upvotes: 1