简体   繁体   中英

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.

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
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM