Search code examples
c#linqsortingsplitunique

Splitting string on unique partrs, sort and concatenate again


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.


Solution

  • Try this single line:

    Console.WriteLine(string.Join(",",myStr.Split(',').Distinct().OrderBy(x=>x)));