LINQ除了考虑只有一个属性 [英] Linq Except considering only one property

查看:137
本文介绍了LINQ除了考虑只有一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个对象的名单

List<object1> obj1 = new List<object1>();

List<object2> obj2 = new List<object2>(); 



我想这样做:

I want to do this:

obj2 = obj2.Except(obj1).ToList();



然而,通过阅读我相似的其他问题,我明白,这不,除非我重写工作平等的。

However, by reading other questions similar to mine, I understand that this doesn't work unless I override Equals.

我不想这样做,但无论OBJ2和OBJ1有一个字符串属性,足以看它们是否相等。如果 obj2.StringProperty 等同于 obj1.StringProperty 则两者可认为是相等的。

I do not want to do that, but both obj2 and obj1 have a string property that is sufficient to see whether they are equal. If obj2.StringProperty is equivalent to obj1.StringProperty then the two can be considered equal.

有什么办法,我可以使用除,但仅使用字符串属性来比较?

Is there any way I can use Except, but by using only the string property to compare?

推荐答案

除了方法要求所涉及的两个集合类型具有相同的元素类型。在这种情况下,元素类型是不同的( object1 Object2的),因此除了是不是一个真正的选择。在这里使用更好的方法是其中,

The Except method requires that the two collection types involved have the same element type. In this case the element types are different (object1 and object2) hence Except isn't really an option. A better method to use here is Where

obj2 = obj2
  .Where(x => !obj1.Any(y => y.StringProperty == x.StringProperty))
  .ToList();

这篇关于LINQ除了考虑只有一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆