-1

I want to define a method which returns true or false if a subset of an enum (first argument) contains an enum element (second element)

In other words, having an enum like:

public enum type { INST, INST_NAME, OPEN_BR, CLOSED_BR};

I wish to define a method like this one:

public bool check (IEnumerable <type> subset , type t)
       {if(subset.Contains t)
            return true;
        else
            return false;
       }

And then call it with:

check(new List<type>{INST, INST_NAME},type.INST);

Which returns true since the list contains INST. So the question is: do you know any more elegant way to implement this method (assuming that it works).

Thank you for your answers!

TwistAndShutter
  • 239
  • 2
  • 15
  • Why not just check if that value of the enum is nothing? – Kat Aug 25 '14 at 17:38
  • Err, null. Nothing is the equivalent in VB.net. – Kat Aug 25 '14 at 17:38
  • 2
    What is the type of "SubsetOfType"? Either I don't understand what you are trying to do, or you are trying do something really wrong with enums – BradleyDotNET Aug 25 '14 at 17:39
  • 1
    You can go by two way: 1. pass the list of enums and check, or 2. define enum as flag (if it suitable). – Hamlet Hakobyan Aug 25 '14 at 17:40
  • 2
    You don't need to define a method, it already exists: [`Contains`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.contains(v=vs.100).ASPX). `return subset.Contains(t);` – D Stanley Aug 25 '14 at 17:41
  • Sounds like he wants a `[Flags]` enum. Check the following question: http://stackoverflow.com/q/1339976/ – Anthony Aug 25 '14 at 18:34
  • Updated trying to implement a first version (still have to test it)...can you find a better/more elegant version? :) – TwistAndShutter Aug 25 '14 at 18:55
  • @LovaJ. Yes - just use `Contains` - there's no need to break it into its own method. – D Stanley Aug 25 '14 at 20:23

2 Answers2

2

Add [Flags] attribute to your enum. Set each option to be represented by an exclusive bit.

For example:

[Flags]
enum LogLevel
{
    App = 1 << 0,
    Exception = 1 << 1,
    Warning = 1 << 2,
    Measurement = 1 << 3,
    User = 1 << 4
}

Then implement your method like this:

bool IsSet(LogLevel levels, LogLevel levelInQuestion)
{
    return (levels & levelInQuestion) > 0;
}

Example Use:

LogLevel logLevels = LogLevel.App | LogLevel.Warning | LogLevel.Exception;
bool logWarnings = IsSet(logLevels, LogLevel.Warning);
Manthess
  • 141
  • 1
  • 4
0

You don't need a separate method to simplify this - you can just use the built-in Contains extension method:

var subset = new List<type>{INST, INST_NAME};

bool check = subset.Contains(type.INST);
D Stanley
  • 149,601
  • 11
  • 178
  • 240