Created
June 13, 2019 13:00
-
-
Save sohjsolwin/1b7246f34681621298b35744b6a19ad6 to your computer and use it in GitHub Desktop.
Union type for bitwise comparisons
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var leadSource = LeadSource.A; | |
var union = LeadSource.A | LeadSource.B | LeadSource.C; | |
Console.WriteLine(union & leadSource); //true | |
Console.WriteLine(union & LeadSource.B); //true | |
Console.WriteLine(union & LeadSource.C); //true | |
Console.WriteLine(union & LeadSource.D); //false | |
var result = "default"; | |
if (union & leadSource) | |
{ | |
result = "test"; | |
} | |
else if ((LeadSource.C | LeadSource.D ) & leadSource) | |
{ | |
result = "test2"; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections; | |
using System.Collections.Generic; | |
using System.Collections.Immutable; | |
using System.Linq; | |
using System.Text; | |
namespace Scrap | |
{ | |
public class Union<T> : IEnumerable<T> where T : IEquatable<T> | |
{ | |
internal ImmutableHashSet<T> _internalSet; | |
private Union(T input) | |
{ | |
_internalSet = new[]{input}.ToImmutableHashSet(); | |
} | |
private Union(IEnumerable<T> input) | |
{ | |
_internalSet = input.ToImmutableHashSet(); | |
} | |
public static Union<T> From(IEnumerable<T> input) | |
{ | |
return new Union<T>(input); | |
} | |
public static Union<T> From(T input) | |
{ | |
return new Union<T>(input); | |
} | |
private static Union<T> From(Union<T> left, T right) | |
{ | |
var combined = left.AsEnumerable().Append(right); | |
return new Union<T>(combined); | |
} | |
private static Union<T> From(Union<T> left, Union<T> right) | |
{ | |
var combined = left.AsEnumerable().Concat(right); | |
return new Union<T>(combined); | |
} | |
public IEnumerator<T> GetEnumerator() | |
{ | |
return _internalSet.GetEnumerator(); | |
} | |
IEnumerator IEnumerable.GetEnumerator() | |
{ | |
return _internalSet.GetEnumerator(); | |
} | |
public static Union<T> operator |(Union<T> left, T right) => From(left, right); | |
public static Union<T> operator |(T left, Union<T> right) => right | left; | |
public static Union<T> operator |(Union<T> left, Union<T> right) => From(left, right); | |
public static bool operator &(Union<T> left, T right) => left.Contains(right); | |
public static bool operator &(T left, Union<T> right) => right & left; | |
public bool Contains(T value) | |
{ | |
return this & value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment