1

我希望删除列表中的所有元素,这些元素可以与另一个不同类型的列表中的元素进行比较,这些元素不具有共同的继承性,但我确实有一个相等功能。一个例子可能会更清楚:

鉴于脚手架

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之外,与相对补充相关的问题似乎都没有处理不同类型的问题。

4

2 回答 2

1

没有任何比赛?

from b in bottles
where !printers.Any(p => isSomeSortOfEqual(b, p))
select b;
于 2012-06-13T13:45:35.050 回答
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
        }
    }
于 2012-06-13T09:48:17.150 回答