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应该是公开的.
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)
不确定与相交和比较相比的速度,但如何:
//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)
| 归档时间: |
|
| 查看次数: |
24677 次 |
| 最近记录: |