发文章
发文工具
撰写
网文摘手
文档
视频
思维导图
随笔
相册
原创同步助手
其他工具
图片转文字
文件清理
AI助手
留言交流
Distinct()方法在MSDN中的示例
public class Product { public string Name { get; set; } public int Code { get; set; } }
Product[] products = { new Product { Name = "apple", Code = 9 }, new Product { Name = "orange", Code = 4 }, new Product { Name = "apple", Code = 10 }, new Product { Name = "lemon", Code = 9 } }; var lstDistProduct = products.Distinct(); foreach (Product p in list1) { Console.WriteLine(p.Code + " : " + p.Name); }
但在实际使用中发现往往无法实现筛选出不重复的数据的目的
查找相关资料获得如下方法:
方法1:使用MoreLinq库
var list1 = products.DistinctBy(x=> x.Code); foreach (Product p in list1) { Console.WriteLine(p.Code + " : " + p.Name); }
方法2:
class ProductComparare : IEqualityComparer<product> { private Func<Product, object> _funcDistinct; public ProductComparare(Func<Product, object> funcDistinct) { this._funcDistinct = funcDistinct; } public bool Equals(Product x, Product y) { return _funcDistinct(x).Equals(_funcDistinct(y)); } public int GetHashCode(Product obj) { return this._funcDistinct(obj).GetHashCode(); } }
var list2 = products.Distinct(new ProductComparare( a => a.Code )); foreach (Product p in list2) { Console.WriteLine(p.Code + " : " + p.Name); }
方法3:
List<Product> list = products .GroupBy(a => a.Code ) .Select(g => g.First()) .ToList(); foreach (Product p in list) { Console.WriteLine(p.Code + " : " + p.Name); }
本人通过第三种方法得到了想要的不重复数据。
来自: 昵称10504424 > 《工作》
0条评论
发表
请遵守用户 评论公约
LINQ学习(五):Select子句
} } List<Student> students = new List<Student>{ new Student {Name="Terry", Scores=new List<int> {97, 72, 81, 60}}, new Student {Name="AI", Scores=new...
linq Distinct的一个简单实现方法
linq Distinct的一个简单实现方法。linq Distinct.[html] view plain copy foreach (List<ReportName> reportNames in query1) { reportNameTemp = new ReportName();fore...
c#范型List的Sort方法详解
SortTestObj1 sObj = (SortTestObj1)obj;第二种带有比较器参数的Sort方法,List中的元素对象不需要继承IComparable接口,但需要额外创建一个对象的比较器,下面的代码中的SortTestObj2类是准备要保存到...
16 C# 第十四章 标准查询运算符
- Linq 函数 where() 筛选 IEnumerable<Student> studentQuery = students.Where( student => student.S...
C#中IEnumerable<T>.Select()、SelectMany()的简单使用
var Lists = PersonLists.public static IEnumerable<TResult> SelectMany<TSource, TResult>(this IEnumerable<TSource...
C#(六)基础篇—数组
C#(六)基础篇—数组。//声明一个用于存储int类型的一维数组并赋值 int[] array1 = new int[2]; array1[0] = 1; array1[1] = 2; //声明同时赋值 int[] array2 = new int[] { 1, 9, 5, 7, 3 }; //另一...
IEnumerable的几个简单用法
例如: public static void Print(IEnumerable myList) { int i = 0; foreach (Object obj in myList) { if (obj is Student)//这个是类型的判断,这里Student是一个类或结构 { Student s = (Student)o...
C# List<T>用法
E.g.: List<string> mList = new List<string>();当前 List 的元素被逐个传递给Predicate委托,并在 List 中向前移动,从第一个元素开始,到最后一个元素结束。表示一个元素为int的链表in...
C#程序设计笔试题
public static int X;<FileSystem>< DriverC ><Dir DirName=”MSDOS622”><File FileName =” Command.com” ></File></Dir><File FileName =”MSDOS.SYS” &g...
微信扫码,在手机上查看选中内容