去除字符串数组或者INT数组中重复的值

其实主要用到Array.Sort(), ArrayList, List就可以对字符串数组或者int数组进行操作

View Code
using System;
using System.Collections;
using System.Collections.Generic;

namespace InsertionSorter
{
    public class InsertionSorter
    {
        //List 可以直接操作,直接ToArray数组
        public static string[] GetString(string[] values)
        {
            List<string> list = new List<string>();
            for (int i = 0; i < values.Length; i++)//遍历数组成员
            {
                if (!list.Contains(values[i]))
                    list.Add(values[i]);
            }

            list.Sort();
            return list.ToArray();
        }

        //可以先排序,再操作,但ArrayList转到Array,需要知道其长度或者强制转换。
        public static int[] Deletecommon(int[] array)
        {
            Array.Sort(array);
            ArrayList save = new ArrayList();
            for (int i = 0; i < array.Length; i++)
            {
                if (!save.Contains(array[i]))
                {
                    save.Add(array[i]);
                }
            }

            //知道长度转换
            int[] result = new int[save.Count];
            save.CopyTo(result);

            //强制转换
            result = (int[])save.ToArray(typeof(Int32));//ToArray(Int32);这样错误,一定要强制类型转换

            //int[] ouput = new int[save.Count];
            //for (int j = 0; j < save.Count; j++)
            //{
            //    ouput[j] = (int)save[j];
            //}
            //ArrayList saveouput1 = ArrayList.Adapter(ouput);

            return result;
        }

        //两个for, 第一个知道所有数的个数,第二个新建个数组,添加不重复的数
        public static String[] RemoveDup(string[] myData)
        {
            if (myData.Length > 0)
            {
                Array.Sort(myData);

                int size = 1; //at least 1 
                for (int i = 1; i < myData.Length; i++)
                    if (myData[i] != myData[i - 1])
                        size++;

                String[] myTempData = new String[size];

                int j = 0;

                myTempData[j++] = myData[0];

                for (int i = 1; i < myData.Length; i++)
                    if (myData[i] != myData[i - 1])
                        myTempData[j++] = myData[i];

                return myTempData;
            }

            return myData;
        }
    }
    public class MainClass
    {
        public static void Main()
        {
            string[] s = new string[10] { "aaa", "aaa", "ccc", "bbb", "bbb", "ddd", "ccc", "aaa", "bbb", "ddd" };
            InsertionSorter.GetString(s);

            InsertionSorter.RemoveDup(s);

            int[] iArrary = new int[] { 1, 13, 3, 3, 6, 10, 10 };
            int[] test = InsertionSorter.Deletecommon(iArrary);

            for (int m = 0; m < test.Length; m++)
                Console.Write("{0} ", test[m]);
            Console.WriteLine();
        }
    }
}
原文地址:https://www.cnblogs.com/binyao/p/3054670.html