sfarzoso
sfarzoso

Reputation: 1610

How to add string.Join separator before each element

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

Answers (2)

jgoday
jgoday

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);
    }
}

C# fiddle

Upvotes: 1

Slai
Slai

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

Related Questions