C# Linq 与对象的一部分相交/除外

标签 c# linq intersect except

我有一个类:

class ThisClass
{
  private string a {get; set;}
  private string b {get; set;}
}

我想使用 Linq 的 Intersect 和 Except 方法,即:

private List<ThisClass> foo = new List<ThisClass>();
private List<ThisClass> bar = new List<ThisClass>();

然后我分别填写两个列表。例如,我想执行以下操作(我知道这是不对的,只是伪代码):

foo[a].Intersect(bar[a]);

我该怎么做?

最佳答案

如果您想要一个要相交的单个属性的列表,那么所有其他漂亮的 LINQ 解决方案都可以正常工作。 但!如果你想在整个类(class)上相交,结果有一个 List<ThisClass>而不是 List<string>您必须编写自己的相等比较器。

foo.Intersect(bar, new YourEqualityComparer());

Except .

public class YourEqualityComparer: IEqualityComparer<ThisClass>
{

    #region IEqualityComparer<ThisClass> Members


    public bool Equals(ThisClass x, ThisClass y)
    {
        //no null check here, you might want to do that, or correct that to compare just one part of your object
        return x.a == y.a && x.b == y.b;
    }


    public int GetHashCode(ThisClass obj)
    {
        unchecked
        {
            var hash = 17;
                            //same here, if you only want to get a hashcode on a, remove the line with b
            hash = hash * 23 + obj.a.GetHashCode();
            hash = hash * 23 + obj.b.GetHashCode();

            return hash;    
        }
    }

    #endregion
}

关于C# Linq 与对象的一部分相交/除外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10633375/

相关文章:

.net - 使用 LINQ 进行多次删除(更具体地说是 Linq2Nhibernate,但是......)

C# linq 距特定路线最近的点

ios - 每当圆形图像与 Xcode 中的 CGRect 相交时发出

ruby - 如何从两个哈希数组中获取联合/交叉/差异并忽略一些键

mysql - 在带有多个表的 MySQL 中模拟一个交集并加入

c# - 使用 PageViewer 和 LayoutPagerAdapter 时的内存管理

c# - 方法注入(inject)(DI、.NET、IOC)

c# - 隐藏查询字符串 MVC3 -ASP.NET

c# - 如何在 WPF 中绘制像素

c# - 将字符串集合转换为字典