Easiest way to convert a list to a comma separated string with a specific property?

I have a list of custom objects. These are actually the objects that I store in the IEnumerable collection. I want to convert the list to a string separated by commas, but I want only one specific property. How do I build a comma separated string with a specific property from a list of user objects?

I know that I can create a comma-separated list using "Foreach / For (int i .... " but I think there is a simple and better way to do this. So what would be so easy?

This is 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 
+6
source share
2 answers

It is very easy, isn't it?

 string sCategories = string.Join(",", categories.Select(x => x.Name)); 
+13
source

Just try with it.

Using this version of the string.Join<string> method, you can shorten copies of your collection before joining.

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

Source: https://habr.com/ru/post/958754/


All Articles