开发者

Manipulate string problem

If I have a string variable with val开发者_运维百科ue as follows :-

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

and I want to manipulate this string and make it as follows:-

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

ie I want to just remove all the duplicates in it, how should I do it?

Please help. Thanks.


Well, here's a LINQ approach:

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

Note that I'm using Trim because your original string has a space before each item, but the result doesn't.

Distinct() doesn't actually guarantee that ordering will be preserved, but the current implementation does so, and that's also the most natural implementation. I find it hard to imagine that it will change.

If you're using .NET 3.5, you'll need a call to .ToArray() after Distinct() as there are fewer string.Join overloads before .NET 4.


You can do the following:

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


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

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


One liner

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

Ordering?

You can as well add OrderBy() in the line to sort your strings if you need to.


I'd personally go for the Linq option in Jon Skeet's answer, so I've also upvoted that, but just to give you another other 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# too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜