2

I have a list of phrases: List<Phrase> where the Phrase object has a property of PhraseId. What I need to do is to get a string that consists of every Id enclosed in single quotes followed by a "," except for the last PhraseId?

In other words I would like to get a string looking something like this:

'id1','id2','id3'

I've seen the LINQ Select command but I think this just gives me another List.

Can anyone suggest how I can do this?

Alan2
  • 23,493
  • 79
  • 256
  • 450

1 Answers1

8

This should work

var result = string.Join(",", phrases.Select(x => $"'{x.PhraseId}'"));

Additional Resources

String.Join Method

Concatenates the elements of a specified array or the members of a collection, using the specified separator between each element or member.

Enumerable.Select Method

Projects each element of a sequence into a new form.

$ - string interpolation (C# Reference)

The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolated expressions. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results. This feature is available in C# 6 and later versions of the language.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141