2

i am trying to figure out how to write a linq query that will return a child collections "name" property as a string.

I have a BO that has a "options" property where the options are the "name" property of each option in an "order" object.

I would like the result to look something like

order.id = 12312
order.date = 12/03/10
order.options = "Option 1 Name, Option 2 Name, Option 3 Name"

I hope this makes sense. thanks for any and all help!

bill
  • 905
  • 5
  • 10
  • 21
  • Could you post the class definition for the classes involved in your query? I think this would help make your question more clear. – Mark Byers Jun 05 '10 at 21:14

2 Answers2

3

While Aggregate will work it has O(n2) performance. If you need better performance you can use string.Join. Unfortunately this method doesn't accept an IEnumerable<string> so you have to also use ToArray to get what you want:

string.Join(", ", options.Select(o => o.Name).ToArray())
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
0

You can use Aggregate:

options.Aggregate((current, next) => current + ", " + next);

Note that this generates a new string for each operation, so if your options list is long you are better off using an old school approach with StringBuilder

Rob
  • 5,525
  • 1
  • 24
  • 26