9

匿名型を使用して、固定された値のリストでグループ化する方法を知っています。私がやりたいことは、実際の値のセットでグループ化することです。

たとえば、この式の結果は 2 です。

new List<HashSet<int>> {
    new HashSet<int> { 4 },
    new HashSet<int> { 4 }
}.GroupBy (x => x).Count()

結果が 1 になるように、これらのセットを同じグループに入れる方法を探しています。Python では、frozenset.

これを行う最もクリーンな方法は何ですか?

4

3 に答える 3

10

HashSet<T>.CreateSetComparerこの目的のために静的メソッドを使用できます。

戻り値

型: System.Collections.Generic.IEqualityComparer> HashSet オブジェクトの詳細な等価性テストに使用できる IEqualityComparer オブジェクト。

new List<HashSet<int>> {
    new HashSet<int> { 4 },
    new HashSet<int> { 4 }
}.GroupBy (x => x, HashSet<int>.CreateSetComparer())
于 2012-08-02T15:45:06.623 に答える
3

(両方のセットを「等しい」としてグループ化することを想定しています。質問はそれほど明確ではありません)

LINQの場合によくあることですが、これを実現するための足場はすでに存在し、実行する必要があるのはIEqualityComparer<T>、適切なメソッドにカスタムを提供することです。この場合、これはこのオーバーロードを使用することを意味します。

IEqualityComparer<ISet<T>>共通部分が両方と同じセットである場合、2つのセットが等しいと宣言するジェネリックは次のとおりです。

class SetComparer<T> : IEqualityComparer<ISet<T>> {
    public bool Equals(ISet<T> lhs, ISet<T> rhs) {
        // null checks omitted
        return lhs.SetEquals(rhs);
    }

    public int GetHashCode(ISet<T> set) {
        // Not the best choice for a hash function in general,
        // but in this case it's just fine.
        return set.Count;
    }
}

そして、同じ傘の下で両方のセットをグループ化する方法は次のとおりです。

new List<HashSet<int>> {
    new HashSet<int> { 4 },
    new HashSet<int> { 4 }
}.GroupBy (x => x, new SetComparer<int>()).Count();
于 2012-08-02T15:40:56.297 に答える
0
var result=new HashSet<int> { 4 }.Union(new HashSet<int> { 4 }).Count();
于 2012-08-02T15:34:46.060 に答える