Display a comma-separated list of values, without a comma.

I have an ASP.Net-MVC application using LinqToSql. I have a subcontract table, a service_lines table, and a Service_lineToSubcontracts mapping / link table that contains subcontract_id and service_line_id. In a subcontract view, I would like to list the relevant service lines.

This works, but has a trailing comma.

<% foreach (var sls in item.Service_lineToSubcontracts) { %> <%= Html.Encode(sls.service_line.service_line_name+", ") %> <% } %> 

I think I should use something like String.Join(", ", item.Service_lineToSubcontracts.ToArray()) , but I'm not sure how to get the array service_line_names.

+4
source share
2 answers

Do it:

 <%= Html.Encode(string.Join(", ", item.ServiceLineNames.Select(x=>x.service_line_name).ToArray())) %> 
+3
source

In the Keltex answer, you can omit the call to the ToArray() method, since the String.Join method works with any IEnumerable<T> .

The hint for a more concise and customizable form is to override the ToString() method of the collection element class, in your case this can be done as:

 public class Service_lineToSubcontract { public Service_line service_line {get; set;} ... public override string ToString() { return service_line.service_line_name; // Or whatever you need } } 

and then use a more concise form:

 <%= Html.Encode(String.Join(", ", item.Service_lineToSubcontracts)) %> 

this hint may not be the best choice in this context, but it simplifies a lot when you have collections of key-value pairs or you need a comma-separated list of descriptions made up of more than one property

0
source

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


All Articles