【知识学习】C# List<T>取并集并去重的两种方法时间消耗比较

C# List取并集并去重的两种方法时间消耗比较


文章目录

  • C# List\取并集并去重的两种方法时间消耗比较
  • 前言
  • 一、两种方法
  • 二、时间计算方法
    • 1.Stopwatch
  • 三、数据
  • 四、总代码
  • 结果总结


前言

  1. 当时是个人要对泛型集合进行合并并且去除重复项,这里有个要点:
    – 对于值类型:可以直接操作。
    对于引用类型:要继承IEqualityComparer()接口实现新的比较方法,来适应你的类型。
  • 结尾有全部代码

一、两种方法

  1. 第一种:不调用其他方法,直接对集合AddRange再Distinct去重
example.AddRange(example);
example.ToList().Distinct();
  1. 第二种:调用Linq的Union方法
example.Union(lastSameExample).ToList();

二、时间计算方法

1.Stopwatch

//时间监视方法
Dictionary<string, double> timeDictionary1 = new Dictionary<string, double>();

Stopwatch stopwatch = new Stopwatch();

stopwatch.Start();
example.AddRange(example);
example.ToList().Distinct();
stopwatch.Stop();
//获取时间(ms)
timeDictionary1.Add("SameList",stopwatch.Elapsed.TotalMilliseconds);

三、数据

取26个字母放入字符串列表:
完全不相同、第一个相同、最后一个相同、中间的相同

 List<string> example = new List<string>()
{
   
    "a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"
};
List<string> notSameExample = new List<string>()
{
   
    "a","bb","cc","dd","ee","ff","gg","hh","ii","jj","kk","ll","mm","nn","oo","pp","qq","rr","ss","tt","uu","vv","ww","xx","yy","zz"
};

List<

你可能感兴趣的:(【知识学习】,【笔记】,C#学习,c#)