C# list集合元素去重的几种方法
一、使用使用HashSet去重
List<int> dataSource = new List<int>() { 1, 2, 2, 3, 4, 5, 5, 7, 8, 10 }; //源数组中共有10个元素HashSet<int> uniqueData = new HashSet<int>(dataSource); //去重之后为8个//输出uniqueData元素为:1,2,3,4,5,7,8,10 元素2和5多次出现的元素被去重
二、使用Linq的Distinct()方法去重
List<int> dataSource = new List<int>() { 1, 2, 2, 3, 4, 5, 5, 7, 8, 10 }; //源数组中共有10个元素var uniqueData = dataSource.Distinct();//输出uniqueData元素为:1,2,3,4,5,7,8,10 元素2和5多次出现的元素被去重
三、使用Linq的GroupBy()方法去重
List<int> dataSource = new List<int>() { 1, 2, 2, 3, 4, 5, 5, 7, 8, 10 }; //源数组中共有10个元素//GroupBy()方法将原始集合中的元素进行分组,根据指定的键或条件进行分组。每个分组都会有一个唯一的键,通过将原始集合分组并选择每个分组中的第一个元素,实现了去重的效果。var uniqueData = dataSource.GroupBy(item => item).Select(group => group.First()).ToList();输出uniqueData元素为:1,2,3,4,5,7,8,10 元素2和5多次出现的元素被去重
四、循环遍历去重
List<int> dataSource = new List<int>() { 1, 2, 2, 3, 4, 5, 5, 7, 8, 10 }; //源数组中共有10个元素var uniqueData = new List<int>();foreach (var item in dataSource){//if (!uniqueData.Any(x => x == item))//if (!uniqueData.Exists(x => x == item))if (!uniqueData.Contains(item)){uniqueData.Add(item);}}//输出uniqueData元素为:1,2,3,4,5,7,8,10 元素2和5多次出现的元素被去重