String manipulation

If I have a string variable with a value as follows: -

string mystring = "TYPE1, TYPE1, TYPE2, TYPE2, TYPE3, TYPE3, TYPE4, TYPE4";

and I want to manipulate this line and make it like this: -

string mystring = "TYPE1,TYPE2,TYPE3,TYPE4";

those. I just want to remove all duplicates in it, how can I do it?

Please, help. Thank.

+5
source share
5 answers

You can do the following:

var parts = mystring.Split(',').Select(s => s.Trim()).Distinct().ToList();
string newString = String.Join(",", parts);
+2
source

Well, here is the LINQ approach:

string deduped = string.Join(",", original.Split(',')
                                          .Select(x => x.Trim())
                                          .Distinct());

Please note that I use Trimbecause the source line has a space before each element, but there is no result.

Distinct()it doesn’t actually guarantee that the ordering will be preserved, but the current implementation does this, and it is also the most natural implementation. It’s hard for me to imagine that this will change.

.NET 3.5, .ToArray() Distinct(), .NET 4 string.Join.

+11
string mystring = "TYPE1, TYPE1, TYPE2, TYPE2, TYPE3, TYPE3, TYPE4, TYPE4";

var split = mystring.Split(',');
var distinct = (from s in split select s).Distinct();
+1
source

Single liner

string result = string.Join(",", mystring.Split(',').Select(s => s.Trim()).Distinct());

Order?

You can also add OrderBy()to a row to sort the rows if you need to.

+1
source

I would personally take the Linq opportunity in Jon Skeet, so I also supported this, but just to give you another option

List<string> parts = new List<String>();
foreach(string split in mystring.Split(','))
    if(!parts.Contains(split))
        parts.Add(split);

string newstr = "";
foreach(string part in parts)
    newstr += part + ",";

This will work in older versions of C #.

+1
source

All Articles