2

I have list of names:

IEnumerable<Name> names;
names = n.GetNames(abc);

It gets list like: Ken, John, Sam,... I want it to show like this: 'Ken', 'John', 'Sam',...

I tried this: string s = string.Join("',", names); but it gives result like: Ken', John', Sam',...

Is there a way to add "'" in front of these names in single line of code?

2 Answers 2

3

Try this.

string s = string.Join(",", names.Select(s => string.Format("'{0}'", s)).ToArray());
Sign up to request clarification or add additional context in comments.

3 Comments

Your solution works great. Just missing ) and ToArray i updated it above. Thanks for the solution!
@NoviceMe that's because you run .NET < 4.0, with .NET 4.0 you can call string.Join with IEnumerable<string>...
@NoviceMe check the first parameter to Join.
3

I think you were almost there:

string s = "'" + string.Join("','", names) + "'";

3 Comments

This will fail however when names.Length == 0 ;p
Of all solutions, mine was the laziest! =D
Also, the most efficient as long as you add a check for the array length.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.