19

List1アイテム{ A, B }List2含み、アイテムを含む{ A, B, C }

私が必要とするのは、{ C }Except Linq 拡張機能を使用するときに返されることです。代わりに返さ{ A, B }れ、式でリストを反転すると、結果は になり{ A, B, C }ます。

例外のポイントを誤解していますか? 使用していない別の拡張機能はありますか?

私はこの問題についてさまざまな投稿を調べて試しましたが、これまでのところ成功していません.

var except = List1.Except(List2); //This is the line I have thus far

編集:はい、単純なオブジェクトを比較していました。を使っIEqualityComparerたことはありませんが、学ぶのは面白かったです。

助けてくれてありがとう。問題は比較子を実装していませんでした。以下のリンクされたブログ投稿と例が参考になります。

4

5 に答える 5

18

リストに参照型を格納している場合は、オブジェクトが等しいかどうかを比較する方法があることを確認する必要があります。それ以外の場合は、同じアドレスを参照しているかどうかを比較してチェックされます。

実装して、 Except()関数IEqualityComparer<T>のパラメーターとして送信できます。役に立つかもしれないブログ投稿を次に示します。

編集:元のブログ投稿のリンクが壊れており、上記に置き換えられました

于 2013-05-29T22:46:31.233 に答える
9

完全を期すために...

// Except gives you the items in the first set but not the second
    var InList1ButNotList2 = List1.Except(List2);
    var InList2ButNotList1 = List2.Except(List1);
// Intersect gives you the items that are common to both lists    
    var InBothLists = List1.Intersect(List2);

編集: リストにはクラスの IEqualityComparer に渡す必要があるオブジェクトが含まれているため、作成されたオブジェクトに基づくサンプル IEqualityComparer を使用すると、例外は次のようになります... :)

// Except gives you the items in the first set but not the second
        var equalityComparer = new MyClassEqualityComparer();
        var InList1ButNotList2 = List1.Except(List2, equalityComparer);
        var InList2ButNotList1 = List2.Except(List1, equalityComparer);
// Intersect gives you the items that are common to both lists    
        var InBothLists = List1.Intersect(List2);

public class MyClass
{
    public int i;
    public int j;
}

class MyClassEqualityComparer : IEqualityComparer<MyClass>
{
    public bool Equals(MyClass x, MyClass y)
    {
        return x.i == y.i &&
               x.j == y.j;
    }

    public int GetHashCode(MyClass obj)
    {
        unchecked
        {
            if (obj == null)
                return 0;
            int hashCode = obj.i.GetHashCode();
            hashCode = (hashCode * 397) ^ obj.i.GetHashCode();
            return hashCode;
        }
    }
}
于 2013-05-29T22:36:59.460 に答える