C#小技巧(二) 用List.Contains方法筛除重复项

C#小技巧—— 用List.Contains方法筛除重复项

一、程序功能

   此程序主要是把List<T>列表类对象中的所有重复项都删除并输出,如果有需要,也可以把重复的项另外输出来供研究。

   举个例子,比如List对象有如下的元素:

List<string> strList = new List<string> { "car""bike""truck""car""plane""car","truck", };

经过处理,输出的结果是:

Car bike truck plane

主要的代码如下,新建一个tempList变量用于存储新链表,然后利用List<T>.Contains方法判断是否重复:

List<string> tempList = new List<string>();

 

            Console.WriteLine("正在处理...");

            foreach (string s in strList)

            {

                if (!tempList.Contains(s))

                    tempList.Add(s);

            }

此方法的好处是代码比较简洁,缺点是要额外的储存tempList链表变量的空间。另外经过实测,Contains方法比较耗时,在链表数量比较大的时候,比如strList有几万几十万个元素的时候,运行比较慢。

如果要知道哪些项目是重复的,可以如下略做改动,可以输出重复的元素:

foreach (string s in strList)

            {

                if (!tempList.Contains(s))

                    tempList.Add(s);

                 else

                    Console.WriteLine(s + "是重复项");

            }

就是加了个else进行判断。

二、程序测试代码

List<string> strList = new List<string> { "car""bike""truck""car""plane""car","truck", };

            List<string> tempList = new List<string>();

 

            Console.WriteLine("原链表如下:");

            foreach (string s in strList)

            {

                Console.WriteLine(s);

            }

 

 

            Console.WriteLine("正在处理...");

            foreach (string s in strList)

            {

                if (!tempList.Contains(s))

                    tempList.Add(s);

                else

                    Console.WriteLine(s + "是重复项");

            }

 

            Console.WriteLine("不重复的链表如下:");

            foreach (string s in tempList)

            {

                Console.WriteLine(s);

            }

 

             Keep the console window open in debug mode.

            Console.WriteLine("Press any key to exit.");

            Console.ReadKey();

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的狐狸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值