C# Distinct去重泛型List
2021/7/16 11:14:34
本文主要是介绍C# Distinct去重泛型List,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
List<int>
去重List<string>
去重List<T>
去重
1、List<int>去重
1 List<int> ilist = new List<int>() { 1, 2, 3, 4, 5, 5,3,1 }; 2 ilist = ilist.Distinct().ToList(); 3 foreach (var item in ilist) 4 { 5 Console.WriteLine(item); 6 }
2、List<string>
去重
List<string> strList = new List<string>() { "4", "4", "5", "6", "6" }; strList = strList.Distinct().ToList(); foreach (var item in strList) { Console.WriteLine(item); }
3、List<T>
去重
public class User { public int Id { get; set; } public string Name { get; set; } } //去重类 public class LambdaComparer<T> : IEqualityComparer<T> { private readonly Func<T, T, bool> _lambdaComparer; private readonly Func<T, int> _lambdaHash; public LambdaComparer(Func<T, T, bool> lambdaComparer) : this(lambdaComparer, EqualityComparer<T>.Default.GetHashCode) { } public LambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash) { if (lambdaComparer == null) throw new ArgumentNullException("比较值为空"); if (lambdaHash == null) throw new ArgumentNullException("数组的Hash值为空"); _lambdaComparer = lambdaComparer; _lambdaHash = lambdaHash; } public bool Equals(T x, T y) { return _lambdaComparer(x, y); } public int GetHashCode(T obj) { return _lambdaHash(obj); } } static void Main(string[] args) { List<User> list = new List<User>() { new User() { Id = 1, Name = "张三" } , new User() { Id = 1, Name = "王五" } , new User() { Id = 1, Name = "张三" } , new User() { Id = 3, Name = "李四" } , }; list = list.Distinct(new LambdaComparer<User>((a, b) => a.Name == b.Name, obj => obj.ToString().GetHashCode())).ToList(); foreach (var item in list) { Console.WriteLine("Id:" + item.Id + ", Name:" + item.Name); } Console.ReadLine(); }
这篇关于C# Distinct去重泛型List的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具