Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expression select and combine fields as single string

Tags:

string

c#

lambda

Let's say , I have tableOne as this structure

Name            Age
=========================
John            34
Ammy            23
Joe             16
Sam             18

What I want to get is likes this format in a single string

John (34) , Ammy (23) , Joe (16) , Sam (18)

How can I get this in a short way using lambda expression ? Thanks :)

like image 260
zey Avatar asked Apr 12 '26 05:04

zey


2 Answers

var result = string.Join(",", tableOne.Select(x=>string.Format("{0} ({1})", x.Name, x.Age)));
like image 163
Damith Avatar answered Apr 14 '26 21:04

Damith


Damith's answer is excellent, and actually cleaner, but if you need to use this with entity framework or some other ORM, you'd probably have to do something like this:

var result = String.Join(" , ", 
    tableOne.Select(x => x.Name + " (" + x.Age + ")"));
like image 30
p.s.w.g Avatar answered Apr 14 '26 19:04

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!