本文介绍了通用列表比较/重复删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 大家好, 我想比较2个自定义对象列表。 这是我的设置: Class< Entity> { string ID; int 金额; public 实体(字符串 _ID, int _Amount) { ID = _ID;金额= _Amount; } } 在下面的代码中我有这个: List< ;实体> E1 = mew List< Entity>(); 列表<实体> E2 = mew List< Entity>(); E1.Add( new 实体( A1, 1 )); E1.Add( new 实体( A1, 1 )); E1.Add( new 实体( B1, 3 )); E1.Add( new 实体( C1, 5 )); E2.Add( new 实体( A1, 1 )); E2.Add( new 实体( D1, 7 )); E2.Add( new 实体( F1, 8 )); E2.Add( new 实体( F1, 8 )); 所以 - 第一个问题 - 如何从这两个列表中删除重复项? E1加倍[A1,1]组合,E2有[F1,8]组合。 我试过用过这个: E1 = E1.distinct()。ToList() E2 = E2.distinct()。ToList()但这没有帮助。 ..任何帮助将不胜感激。 问题#2。 我想要返回第3个列表,其中包含所有项目列表E1,但不在列表#2中。 我尝试过这个LINQ查询: var 区别=(来自项目 E2 where !E1.Contains(item) select item)。ToList(); 虽然这不是安静的工作 - 它返回两个都存在的项目......所以我在这里安静迷失....我正在考虑在Entity类上实现IComparable接口,但不是很确定......如果你能至少向我展示正确的道路,或者举一些例子让我的大脑开启,我将不胜感激。 提前致谢!解决方案 查看我过去的回答:如何比较一个数组中的日期 [ ^ ]。 Hello guys,I am trying to compare 2 list of custom objects.Here is my setup:Class <Entity>{ string ID; int Amount; public Entity(string _ID, int _Amount) { ID = _ID; Amount = _Amount; }}In the further code I have this:List<Entity> E1 = mew List<Entity>();List<Entity> E2 = mew List<Entity>();E1.Add(new Entity("A1", 1));E1.Add(new Entity("A1", 1));E1.Add(new Entity("B1", 3));E1.Add(new Entity("C1", 5));E2.Add(new Entity("A1", 1));E2.Add(new Entity("D1", 7));E2.Add(new Entity("F1", 8));E2.Add(new Entity("F1", 8));So - 1st question - how to remove duplicates from these 2 lists? E1 has doubled ["A1", 1] combination and E2 has ["F1", 8] combination.I have tried using this:E1 = E1.distinct().ToList()E2 = E2.distinct().ToList()But that did not help... any help would be appreciated.Question #2.I want to return 3rd list which would contain the items that are in list E1, but not in list #2.I have tried this LINQ query:var distinction = (from item in E2 where !E1.Contains(item) select item).ToList();Though that does not quiet work - it returns items that are present in both... so I'm quiet lost in here.... I was thinking about implementing IComparable interface on Entity class, but not really sure... would appreciate if you could at least show me the right path or give some example to turn my brains on :)Thanks in advance! 解决方案 这篇关于通用列表比较/重复删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-19 18:38