Easiest way to convert list to a comma separated string by a Specific Property?

.net c# entity-framework linq

Question

I have a list of custom objects that I am actually keeping in an IEnumerable collection as entities. How do I create a comma separated string with a certain property from a custom object list? I want to convert the list to a comma separated string, but I only want one particular attribute.

I am aware that I can create a comma-separated list using a"Foreach / For (int i .... " however, I believe there is a quick and better method to do this. What would be that quick approach?

Here's my list.

IEnumerable<BAL.Category> categories = chklCategories.CheckedItems.Cast<BAL.Category>();
            //Category object has a property called Name , I want the list from that property
1
6
11/25/2013 5:16:27 AM

Accepted Answer

Isn't this really simple?

string sCategories = string.Join(",", categories.Select(x => x.Name));
13
11/25/2013 5:03:42 AM

Popular Answer

Just give it a shot.

Utilizing this variation of thestring.Join<string> you can cut down on the number of copies in your collection before enrolling.

static string CombineList(IEnumerable categories)
{
  return string.Join<string>(",", categories.Select(x => x.Name));
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow