我希望删除列表中的所有元素,这些元素可以与不同类型的另一个列表的元素进行比较,这些元素不具有共同的能力,但我确实有一个相等的函数。一个例子可能会更清楚:
给予脚手架
bool isSomeSortOfEqual(Bottle b, Printer p){
//implementation
}
List<Bottle> bottles = getBottles();
List<Printer> printers = getPrinters();
我想做这样的事情:
List<Bottle> result = bottles.Except(printers, (b, p => isSomeSortOfEqual(b, p));
.NET中是否有内置版本,或者我应该手动实现它?关于相对补充或者除了在stackoverflow上的.NET之外,没有任何问题似乎涉及具有不同类型。
答案 0 :(得分:1)
这个怎么样?基本想法是将列表转换为List<object>
,然后使用.Except并使用IEqualityComparer<object>
class A
{
public int Ai;
}
class B
{
public int Bi;
}
public class ABComparer : IEqualityComparer<object>
{
public bool Equals(object x, object y)
{
A isA = x as A ?? y as A;
B isB = x as B ?? y as B;
if (isA == null || isB == null)
return false;
return isA.Ai == isB.Bi;
}
public int GetHashCode(object obj)
{
A isA = obj as A;
if (isA != null)
return isA.Ai;
B isB = obj as B;
if (isB != null)
return isB.Bi;
return obj.GetHashCode();
}
}
class Program
{
static void Main(string[] args)
{
List<object> As = new List<object> { new A { Ai = 1 }, new A { Ai = 2 }, new A { Ai = 3 } };
List<object> Bs = new List<object> { new B { Bi = 1 }, new B { Bi = 1 } };
var except = As.Except(Bs, new ABComparer()).ToArray();
// Will give two As with Ai = 2 and Ai = 3
}
}
答案 1 :(得分:1)
没有任何匹配?
from b in bottles
where !printers.Any(p => isSomeSortOfEqual(b, p))
select b;