Click here to Skip to main content
15,894,539 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have four lists boxes with multiple selection.

list a,b,c,d;

i am getting its values by below code.

C#
string a = String.Join(",", listA.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Text));

string b = String.Join(",", listB.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Text));

string c = String.Join(",", listC.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Text));

string d = String.Join(",", listD.Items.OfType<ListItem>().Where(r => r.Selected).Select(r => r.Text));


string values=a+b+c+d;


My question is when i select values it result like.

,b,c,d OR
a,,c,d OR
a,b,c,

I need the result like

b,c,d OR
a,c,d
a,b,c

There are useless commas how we remove it.

What I have tried:

C#
<pre lang="C#">

string a = String.Join(&quot;,&quot;, listA.Items.OfType&lt;ListItem&gt;().Where(r =&gt; r.Selected).Select(r =&gt; r.Text));

string b = String.Join(&quot;,&quot;, listB.Items.OfType&lt;ListItem&gt;().Where(r =&gt; r.Selected).Select(r =&gt; r.Text));

string c = String.Join(&quot;,&quot;, listC.Items.OfType&lt;ListItem&gt;().Where(r =&gt; r.Selected).Select(r =&gt; r.Text));

string d = String.Join(&quot;,&quot;, listD.Items.OfType&lt;ListItem&gt;().Where(r =&gt; r.Selected).Select(r =&gt; r.Text));


string values=a+b+c+d;

</pre>
Posted
Updated 17-Oct-16 21:57pm
Comments
Suvendu Shekhar Giri 18-Oct-16 3:07am    
so, is your question "How to remove trailing comma in a string?" ?
shaprpuff 18-Oct-16 3:23am    
yes
Suvendu Shekhar Giri 18-Oct-16 3:29am    
Please check the solution if it helps, otherwise let me know.
F-ES Sitecore 18-Oct-16 3:57am    
As well as using TrimEnd you can also look to use the linq "Aggregate" command rather than Join which should avoid the comma being there in the first place. Google "c# linq aggregate" for examples.

try this

C#
string a = String.Join(",", listA.Items.OfType<ListItem>().Where(r => r.Selected && !string.IsNullOrWhiteSpace(r.Text)).Select(r => r.Text));
 
Share this answer
 
You can use String.TrimEnd Method [^]

Something like -
C#
values = values.TrimEnd(',');


Hope, it helps :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900