2

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 :)

3
  • 3
    Have you tried anything? Commented Jul 30, 2013 at 6:10
  • What have I tried ? Just select as a List Siva :) tableOne.ToList() Commented Jul 30, 2013 at 6:12
  • @zey I think what Siva means is, what have you tried to do to produce a string like that? Even if your attempt didn't work or didn't even compile, at least it shows that you tried something. People on SO are generally forgiving of bad code, but we usually want to see some code :P Commented Jul 30, 2013 at 6:21

2 Answers 2

8
var result = string.Join(",", tableOne.Select(x=>string.Format("{0} ({1})", x.Name, x.Age)));
Sign up to request clarification or add additional context in comments.

Comments

4

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 + ")"));

1 Comment

BTW you don't need to call ToString() on integer when concatenating it with string

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.