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

Dav*_*her 21 c# linq except intersect

我上课了:

class ThisClass
{
  private string a {get; set;}
  private string b {get; set;}
}
Run Code Online (Sandbox Code Playgroud)

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

private List<ThisClass> foo = new List<ThisClass>();
private List<ThisClass> bar = new List<ThisClass>();
Run Code Online (Sandbox Code Playgroud)

然后我分别填写两个列表.我想做,例如(我知道这是不对的,只是伪代码),如下:

foo[a].Intersect(bar[a]);
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Ser*_*kiy 28

也许

// returns list of intersecting property 'a' values
foo.Select(f => f.a).Intersect(bar.Select(b => b.a));
Run Code Online (Sandbox Code Playgroud)

BTW财产a应该是公开的.

  • 这将返回属性的集合。我正在寻找对象集合的返回。请参阅下面 Patryk 的评论。 (2认同)

Pat*_*iek 23

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

foo.Intersect(bar, new YourEqualityComparer());
Run Code Online (Sandbox Code Playgroud)

与...相同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
}
Run Code Online (Sandbox Code Playgroud)


Zac*_*son 5

不确定与相交和比较相比的速度,但如何:

//Intersect
var inter = foo.Where(f => bar.Any(b => b.a == f.a));
//Except - values of foo not in bar
var except = foo.Where(f => !bar.Any(b => b.a == f.a));
Run Code Online (Sandbox Code Playgroud)

  • 这是一个 O(n * m) 算法,而 `Intersect` 和 `Except` 都是 `O(n + m)`。这让你的情况变得更糟。它还多次迭代 `bar`,这在各种情况下都可能是一个主要问题(它可能不会在每次迭代中产生相同的结果,它可能会在每次迭代时查询数据库或执行昂贵的计算,它可能会产生副作用)迭代时引起的,等等。 (5认同)