Reputation: 261
I'm just learning C#, so please don't blame me if the solution is obvious.
I have comma-delimeted string. I want to split it, remove duplicates from splitted array, sort result array and then concatenate again.
E.g. for string "3,a,b,3,a,c,s,3,1,2,3,3"
result should be: "1,2,3,a,b,c,s"
What I've tried so far is next code:
static void Main(string[] args)
{
string myStr = "3,a,b,3,a,c,s,3,1,2,3,3";
string[] temp = myStr.Split(',');
string res = "";
List<string> myList = new List<string>();
foreach (var t in temp)
{
if (myList.Contains(t)==false){
myList.Add(t);
}
}
myList.Sort();
foreach(var t in myList){
res+=t +",";
}
res = res.Substring(0, res.Length - 1);
Console.WriteLine(res);
}
But I believe there is more effificent way..
Thanks in advise.
Upvotes: 1
Views: 2954
Reputation: 35843
Try this single line:
Console.WriteLine(string.Join(",",myStr.Split(',').Distinct().OrderBy(x=>x)));
Upvotes: 9