How do I remove duplicates from a C# array?

后端 未结 27 2286
北海茫月
北海茫月 2020-11-22 07:53

I have been working with a string[] array in C# that gets returned from a function call. I could possibly cast to a Generic collection, but I was w

27条回答
  •  难免孤独
    2020-11-22 08:29

    Tested the below & it works. What's cool is that it does a culture sensitive search too

    class RemoveDuplicatesInString
    {
        public static String RemoveDups(String origString)
        {
            String outString = null;
            int readIndex = 0;
            CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;
    
    
            if(String.IsNullOrEmpty(origString))
            {
                return outString;
            }
    
            foreach (var ch in origString)
            {
                if (readIndex == 0)
                {
                    outString = String.Concat(ch);
                    readIndex++;
                    continue;
                }
    
                if (ci.IndexOf(origString, ch.ToString().ToLower(), 0, readIndex) == -1)
                {
                    //Unique char as this char wasn't found earlier.
                    outString = String.Concat(outString, ch);                   
                }
    
                readIndex++;
    
            }
    
    
            return outString;
        }
    
    
        static void Main(string[] args)
        {
            String inputString = "aAbcefc";
            String outputString;
    
            outputString = RemoveDups(inputString);
    
            Console.WriteLine(outputString);
        }
    

    }

    --AptSenSDET

提交回复
热议问题