12

Here is my table ,

myTable
-------------
id      name       age
-------------------------
1     NameOne       10
2     NameTwo       11
3     NameThree     12
4     NameFour      13  
5     NameFive      14

I retrieve my table likes ,

var _myList = DBContext.myTables.ToList();

I want to get string likes

"NameOne,NameTwo,NameThree,NameFour,NameFive"

How can I do this in shorter way ?

3 Answers 3

33

Use String.Join

string names = String.Join(",", _myList.Select(x => x.Name));

Or you can even avoid loading other columns from DB:

string names = String.Join(",", DBContext.myTables.Select(x => x.Name));
Sign up to request clarification or add additional context in comments.

Comments

10

It sounds like you want:

string names = string.Join(",", DBContext.myTable.Select(x => x.Name));

You don't need to go through an intermediate list - and in fact it's more efficient not to. With this query, only the names will be fetched from the database.

5 Comments

May I dare to correct one small mistake (big fan of Jon) :), you need to convert it into an Array, because string.Join expects a string array.
@bazz, actually there is an overload that accepts IEnumerable.
@bazz: It depends on the version of .NET you're using. The overload list was significantly expanded in .NET 4.
@Andrei Really? Can you point me to some reference? MSDN
@bazz: Look at the documentation you're pointing to - on the left side of the screen there's an overload list...
0
var _myList = DBContext.myTables.ToList();
var names = _myList.Select(x => x.name);
var formattedStrings = string.Join(", ", names);

Comments

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.