C# 删除数组中重复元素实例

作者:袖梨 2022-06-25

例1

 代码如下 复制代码

string[] stringArray = { “aaa”, “bbb”, “aaa”, “ccc”, “bbb”, “ddd”, “ccc”, “aaa”, “bbb”, “ddd” };
//List用于存储从数组里取出来的不相同的元素
List listString = new List();
foreach (string eachString in stringArray)
{
if (!listString.Contains(eachString))
listString.Add(eachString);
}
//最后从List里取出各个字符串进行操作
foreach (string eachString in listString)
{
Console.Write(eachString); //打印每个字符串
}

例2

 代码如下 复制代码

//1.把字符串转换成数组

string ls_str="122,158,141,236,896,123,122,158,141";

string[] str_num=ls_str.Split(',');

  //2.定义ArrayList,判断数组中重复字段不添加到 ArrayList对象中

   ArrayList al = new ArrayList();
   for (int i = 0; i < str_num.Length; i++)
    {

  //判断是否已经存在
     if (al.Contains(str_num[i]) == false)
        {
           al.Add(str_num[i]);
         }

    }

  //3.将arrayList转换成数组
   str_num= new String[al.Count];
   str_num= (string[])al.ToArray(typeof(string));

相关文章

精彩推荐