Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lambda list to combine string

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 ?

like image 806
zey Avatar asked Jul 02 '13 08:07

zey


2 Answers

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));
like image 102
Andrei Avatar answered Nov 02 '22 00:11

Andrei


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.

like image 41
Jon Skeet Avatar answered Nov 01 '22 23:11

Jon Skeet