How do I remove duplicates from a C# array?

后端 未结 27 2839
北海茫月
北海茫月 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:48

    This might depend on how much you want to engineer the solution - if the array is never going to be that big and you don't care about sorting the list you might want to try something similar to the following:

        public string[] RemoveDuplicates(string[] myList) {
            System.Collections.ArrayList newList = new System.Collections.ArrayList();
    
            foreach (string str in myList)
                if (!newList.Contains(str))
                    newList.Add(str);
            return (string[])newList.ToArray(typeof(string));
        }
    

提交回复
热议问题