标签:style count() 表达 操作 pre var get 序列 char
在项目里用lambda的Distinct方法进行对象去重操作发现返回的数据仍然还是没有去重的数据,百度搜索后发现Distinct只是将List容器中的各个对象地址进行比较来进行去重。
public class Employee { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } public char Sex { get; set; } } class Program { public static void Main(string[] args) { var temp1 = new Employee() { ID = 1, Age = 24, Name = "frank", Sex = ‘m‘ }; data.Add(temp1); data.Add(temp1); var datanew = data.Distinct(); Console.WriteLine(datanew.Count()); Console.ReadKey(); } }
这并不能达到我们将不同对象在序列化后进行对象去重的要求。
去重主要思路:在lambda表达式GrouBy分组后只取每组第一条的数据来达到筛选唯一数据的结果,实现代码如下
public class Employee { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } public char Sex { get; set; } } class Program { public static void Main(string[] args) { List<Employee> data = new List<Employee>() { new Employee() { ID = 1, Age = 22, Name = "阿飞", Sex = ‘m‘ }, new Employee() { ID = 1, Age = 22, Name = "阿飞", Sex = ‘m‘ }, new Employee() { ID = 2, Age = 23, Name = "阿飞", Sex = ‘m‘ }, }; var datanew = data.GroupBy(e => e.ID).Select(e => e.First()); Console.WriteLine(datanew.Count()); Console.ReadKey(); } }
标签:style count() 表达 操作 pre var get 序列 char
原文地址:http://www.cnblogs.com/leeafei/p/7373571.html