List去重

Enumerable.Distinct 方法 是常用的LINQ扩展方法,属于System.Linq的Enumerable方法,可用于去除数组、集合中的重复元素,还可以自定义去重的规则。

有两个重载方法:

复制代码
复制代码
        //
        // 摘要: 
        //     通过使用默认的相等比较器对值进行比较返回序列中的非重复元素。
        //
        // 参数: 
        //   source:
        //     要从中移除重复元素的序列。
        //
        // 类型参数: 
        //   TSource:
        //     source 中的元素的类型。
        //
        // 返回结果: 
        //     一个 System.Collections.Generic.IEnumerable<T>,包含源序列中的非重复元素。
        //
        // 异常: 
        //   System.ArgumentNullException:
        //     source 为 null。
        public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source);
        //
        // 摘要: 
        //     通过使用指定的 System.Collections.Generic.IEqualityComparer<T> 对值进行比较返回序列中的非重复元素。
        //
        // 参数: 
        //   source:
        //     要从中移除重复元素的序列。
        //
        //   comparer:
        //     用于比较值的 System.Collections.Generic.IEqualityComparer<T>。
        //
        // 类型参数: 
        //   TSource:
        //     source 中的元素的类型。
        //
        // 返回结果: 
        //     一个 System.Collections.Generic.IEnumerable<T>,包含源序列中的非重复元素。
        //
        // 异常: 
        //   System.ArgumentNullException:
        //     source 为 null。
        public static IEnumerable<TSource> Distinct<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer);    
复制代码
复制代码

第一个方法不带参数,第二个方法需要传一个System.Collections.Generic.IEqualityComparer<T>的实现对象

1.值类型元素集合去重

List<int> list = new List<int> { 1, 1, 2, 2, 3, 4, 5, 5 };
list.Distinct().ToList().ForEach(s => Console.WriteLine(s));

执行结果是:1 2 3 4 5

2.引用类型元素集合去重

首先自定义一个Student类

使用不到参数的Distinct方法去重

复制代码
复制代码
            List<Student> list = new List<Student>() { 
                new Student("James",1,"Basketball"),
                new Student("James",1,"Basketball"),
                new Student("Kobe",2,"Basketball"),
                new Student("Curry",3,"Football"),
                new Student("Curry",3,"Yoga")
            };
            list.Distinct().ToList().ForEach(s => Console.WriteLine(s.ToString()));   
复制代码
复制代码

执行结果:

可见,并没有去除重复的记录。

不带comparer参数的Distinct方法是使用的IEqualityComparer接口的默认比较器进行比较的,对于引用类型,默认比较器比较的是其引用地址,程序中集合里的每一个元素都是个新的实例,引用地址都是不同的,所以不会被作为重复记录删除掉。

因此,我们考虑使用第二个重载方法。

新建一个类,实现IEqualityComparer接口。注意GetHashCode方法的实现,只有HashCode相同才会去比较

复制代码
复制代码
    public class Compare:IEqualityComparer<Student>
    {
        public bool Equals(Student x,Student y)
        {
            return x.Id == y.Id;//可以自定义去重规则,此处将Id相同的就作为重复记录,不管学生的爱好是什么
        }
        public int GetHashCode(Student obj)
        {
            return obj.Id.GetHashCode();
        }
    }
复制代码
复制代码

然后调用

list.Distinct(new Compare()).ToList().ForEach(s => Console.WriteLine(s.ToString()));

执行结果:

我们按照Id去给这个集合去重成功!

3.如何编写一个具有扩展性的去重方法

复制代码
    public class Compare<T, C> : IEqualityComparer<T>
    {
        private Func<T, C> _getField;
        public Compare(Func<T, C> getfield)
        {
            this._getField = getfield;
        }
        public bool Equals(T x, T y)
        {
            return EqualityComparer<C>.Default.Equals(_getField(x), _getField(y));
        }
        public int GetHashCode(T obj)
        {
            return EqualityComparer<C>.Default.GetHashCode(this._getField(obj));
        }
    }
    public static class CommonHelper
    {
        /// <summary>
        /// 自定义Distinct扩展方法
        /// </summary>
        /// <typeparam name="T">要去重的对象类</typeparam>
        /// <typeparam name="C">自定义去重的字段类型</typeparam>
        /// <param name="source">要去重的对象</param>
        /// <param name="getfield">获取自定义去重字段的委托</param>
        /// <returns></returns>
        public static IEnumerable<T> MyDistinct<T, C>(this IEnumerable<T> source, Func<T, C> getfield)
        {
            return source.Distinct(new Compare<T, C>(getfield));
        }
    }
复制代码

调用:

list.MyDistinct(s=>s.Id).ToList().ForEach(s => Console.WriteLine(s.ToString()));

用到了泛型、委托、扩展方法等知识点。可以用于任何集合的各种去重场景

转载于:https://www.cnblogs.com/ztf20/p/9117844.html

### 列表方法概述 在 Python 中,可以通过多种方式实现列表的操作。以下是几种常见的方法及其对应的源码示例。 --- #### 方法一:使用集合 `set` 由于集合中的元素是唯一的,因此可以利用这一特性来快速除列表中的复项[^1]。 ```python def remove_duplicates_with_set(lst): return list(set(lst)) example_list = [1, 2, 2, 3, 4, 4, 5] result = remove_duplicates_with_set(example_list) print(result) # 输出可能为 [1, 2, 3, 4, 5], 集合不保证顺序 ``` 此方法简单高效,但由于集合本身无序,最终返回的结果可能会丢失原始列表中元素的顺序。 --- #### 方法二:保持原顺序并使用辅助集合 如果需要保留原始列表中元素的顺序,则可以在遍历过程中借助一个额外的集合记录已处理过的元素[^1]。 ```python def remove_duplicates_keep_order(lst): seen = set() result = [] for item in lst: if item not in seen: seen.add(item) result.append(item) return result example_list = [1, 2, 2, 3, 4, 4, 5] result = remove_duplicates_keep_order(example_list) print(result) # 输出为 [1, 2, 3, 4, 5] ``` 这种方法既实现了又保留了原有顺序,适用于大多数实际场景。 --- #### 方法三:基于字典键唯一性的解法 (Python 3.7+) 自 Python 3.7 起,内置字典默认按插入顺序保存键值对。因此也可以通过构建临时字典的方式完成,并自动维护输入数据的相对位置关系[^1]。 ```python from collections import OrderedDict def remove_duplicates_with_dict(lst): return list(OrderedDict.fromkeys(lst)) example_list = [1, 2, 2, 3, 4, 4, 5] result = remove_duplicates_with_dict(example_list) print(result) # 输出为 [1, 2, 3, 4, 5] ``` 该方案性能较好,在支持版本范围内推荐优先采用。 --- #### 方法四:列表推导式配合条件判断 对于小型项目或者学习目的而言,还可以尝试用更简洁的一行代码形式表达逻辑: ```python def remove_duplicates_with_comprehension(lst): temp = [] [temp.append(x) for x in lst if x not in temp] return temp example_list = [1, 2, 2, 3, 4, 4, 5] result = remove_duplicates_with_comprehension(example_list) print(result) # 输出为 [1, 2, 3, 4, 5] ``` 尽管语法较为紧凑直观,但其时间复杂度较高(O(n²)),不适合大规模数据集处理需求[^1]。 --- 以上介绍了四种不同的列表技术以及它们各自的优缺点分析。开发者应根据具体应用场景选择最合适的策略实施编码工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值