Click here to Skip to main content
15,888,202 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys,

I want to remove comma separated duplicate string values like :
C#
string ReturnStr = "2,5,12,35,2,12,78,45,35,78";

And I need :
C#
string ReturnStr = "2,5,12,35,78,45";

I can separate it but thats a long method, can any one tell me how can I do it shortly.
Posted
Comments
JoCodes 6-Jan-14 6:51am    
Which is the long method you tried?

On top of Anuja solution.

Try this simple one.

C#
string ReturnStr = "2,5,12,35,2,12,78,45,35,78";
        string temp="";
        ReturnStr.Split(',').Distinct().ToList().ForEach(k => temp += k + ",");
        ReturnStr = temp.Trim(',');
 
Share this answer
 
and even simpler one. I took answer 2 and simplified it


C#
string ReturnStr = "2,5,12,35,2,12,78,45,35,78";
string temp = string.Join(",", ReturnStr.Split(',').Distinct().ToArray());
 
Share this answer
 
Comments
Santhosh Ks 28-Jun-19 4:58am    
excellent.

selectexcs = selectexcs.TrimEnd(',').Trim();
for (dynamic i = 0, repl = new[,] { { ",,", "," }, { " ", "" } }; i < repl.Length / 2; i++)
{
selectexcs = selectexcs.Replace(repl[i, 0], repl[i, 1]);
selectexcs = selectexcs.Trim();
}
selectexcs= string.Join(",", selectexcs.Split(',').Distinct().ToArray());
numberofbagscanselled = selectexcs.Count(c => c == ',') +1;//duplication of strings separated with camma.
Try this
C#
string ReturnStr = "2,5,12,35,2,12,78,45,35,78";
            string[] words = ReturnStr.Split(',');
            List<string> list = new List<string>();
            foreach (string word in words)
            {
                if ( ! list.Contains(word))
                    list.Add(word);
            }

Updated
try this also
C#
if (ReturnStr .substring(ReturnStr .length-1, ReturnStr .length) == ",") {
        ReturnStr = ReturnStr .substring(0, ReturnStr .length-1);
    }
    TextBox1.Text = ReturnStr ;
 
Share this answer
 
v3
Comments
Mas11 6-Jan-14 7:03am    
Below Method gives an error : Index and length must refer to a location within the string.
Parameter name: length
Mas11 6-Jan-14 7:19am    
Thanks ! your first method work perfectly.
Anuja Pawar Indore 6-Jan-14 7:34am    
Thanks............ Yes 2nd option is not working

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