Lars Holm Jensen
Lars Holm Jensen

Reputation: 1695

Are there any value type collection in C#?

Are there any collections with value type semantics in C#? So that set1 equals set2 if they contain the same structs/primitives? Maybe in the same order.

Upvotes: 4

Views: 375

Answers (1)

LVBen
LVBen

Reputation: 2061

HashSet is pretty close, but == doesn't compare the values in the collections. SetEquals will return true if they contain the same values. However, the order doesn't factor in. You can use SequenceEqual if order is important.

  static void Main(string[] args)
  {
     HashSet<int> set1 = new HashSet<int> { 1, 2, 3 };
     HashSet<int> set2 = new HashSet<int> { 2, 1, 3 };
     HashSet<int> set3 = new HashSet<int> { 1, 2, 3 };
     Console.WriteLine(set1.SetEquals(set2));          // True
     Console.WriteLine(set1.SequenceEqual<int>(set2)); // False
     Console.WriteLine(set1.SequenceEqual<int>(set3)); // True
  }

Upvotes: 5

Related Questions