一、程序功能
此程序主要是把List
举个例子,比如List对象有如下的元素:
List<string> strList = new List<string> { "car", "bike", "truck", "car", "plane", "car","truck", };
经过处理,输出的结果是:
Car bike truck plane
主要的代码如下,新建一个tempList变量用于存储新链表,然后利用List
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();