1

There are two HashSet sequences. I need to count the result of union. It should look like this:

    sequence1.UnionWith(sequence2);
    return sequence1.Count;

But I need to ensure that the original sequences do not change. I used a simple search, but it very slows down the program

    var newHashkSet = new HashSet<string>(sequence1);
    foreach (var s2 in sequence2.Where(s2 => newHashkSet.SingleOrDefault(x => x == s2) == null)) {
        newHashkSet.Add(s2);
    }
    return newHashkSet.Count();

Is there a more elegant solution?

HuckFin.7b
  • 325
  • 4
  • 13
  • What do you mean by _"the original sequences do not change"_? Hashsets are unordered by definition. See also [Does HashSet preserve insertion order?](http://stackoverflow.com/questions/657263/does-hashset-preserve-insertion-order). – CodeCaster Mar 26 '17 at 17:06
  • I mean that after using sequence1.UnionWith(sequence2) sequence1 is changing – HuckFin.7b Mar 26 '17 at 17:07

2 Answers2

4

Use an ImmutableHashSet.

https://msdn.microsoft.com/en-us/library/dn467171(v=vs.111).aspx

By definition, immutable hash sets do not change. When you form the union of two immutable hash sets, the result is a third immutable hash set, not the mutation of either of the inputs.

Eric Lippert
  • 647,829
  • 179
  • 1,238
  • 2,067
2

Another quick but not memory efficient way is that You can create a copy of hashSet and then do the union

var newset = new HashSet<string>(sequence1);
newset.UnionWith(sequence2);
netset.count
Haseeb Asif
  • 1,766
  • 2
  • 23
  • 41