2

setA と setB の 2 つの HashSet があります。

  1. setA と setB の補数をどのように見つけることができますか?
  2. 交差点のコードは、交差点を見つけるための最良の方法ですか?

コード

 string stringA = "A,B,A,A";
 string stringB = "C,A,B,D";

 HashSet<string> setA = new HashSet<string>(stringA.Split(',').Select(t => t.Trim()));
 HashSet<string> setB = new HashSet<string>(stringB.Split(',').Select(t => t.Trim()));

 //Intersection - Present in A and B
 HashSet<string> intersectedSet = new HashSet<string>( setA.Intersect(setB));

 //Complemenet - Present in A; but not present in B

更新

OrdianlIgnoreCase大文字 と小文字を区別しないモードで HashSet<string>.Contains() メソッドを使用する方法

参考

  1. HashSet<T> と List<T> の違いは何ですか?
  2. IEnumerable.Intersect() を使用した複数のリストの交差
  3. 2 つのハッシュセットの比較
  4. 2 つのハッシュセットを比較しますか?
  5. C# で 2 つのコレクションの補数を見つける最も簡単な方法
4

2 に答える 2

2

1-setAとsetBの補数をどのように見つけることができますか?

使用するHashSet<T>.Except Method

//Complemenet - Present in A; but not present in B
HashSet<string> ComplemenetSet = new HashSet<string>(setA.Except(setB));

次の文字列で試してください。

string stringA = "A,B,A,E";
string stringB = "C,A,B,D";

ComplementSetには次のものが含まれますE

2-交差点のコードは交差点を見つけるための最良の方法ですか?

おそらくそうだ

于 2012-11-30T09:32:23.627 に答える
2

ExceptAまたはBの補数を取得するために使用できます。対称補数を取得するには、を使用しますSymmetricExceptWith

setA.SymmetricExceptWith(setB);

これにより、が変更 されることに注意してくださいsetA。交差点を取得するには、2つの方法がIntersectあります。新しいを作成する方法HashSetIntersectWith、最初の方法を変更する方法です。

// setA and setB unchanged
HashSet<string> intersection = setA.Intersect(setB);

// setA gets modified and holds the result
setA.IntersectWith(setB);
于 2012-11-30T09:33:51.347 に答える