❔ Compare Enum Values with submitted value

Hi, how can I compare the submitted value with values in an enum without using switch-case? For example,
public enum Weekends {
Saturday,
Sunday
}

[HttpPost]
public async Task<IActionResult> Create([FromForm] Day day)
{
var weekendvalues = Enum.GetNames(typeof(Weekends));
var values = string.Join(", ", weekendvalues);

if (day.Day != values) {
// Do something
}
else if () {
// Some other things
}
}
public enum Weekends {
Saturday,
Sunday
}

[HttpPost]
public async Task<IActionResult> Create([FromForm] Day day)
{
var weekendvalues = Enum.GetNames(typeof(Weekends));
var values = string.Join(", ", weekendvalues);

if (day.Day != values) {
// Do something
}
else if () {
// Some other things
}
}
44 Replies
CoreVisional
CoreVisionalOP3y ago
I hope this gives more context than my previous post on what I'm trying achieve
Servator
Servator3y ago
You can use compare with values i suppose But why you are avoiding using switch case ?
CoreVisional
CoreVisionalOP3y ago
I'm not, I'm just looking to see if it's possible to use it within the if statement rather than having another switch-case block just for that one comparison, like if (Model.State.IsValid && day.Day != values && day.File != null), so that means I have a switch-case block just for day.Day != values the compareto()?
Servator
Servator3y ago
Basicly Enum values are int actually underlying type is int If you count Monday as a 0 5 and 6 is weekends
CoreVisional
CoreVisionalOP3y ago
I'm guessing it's not pretty to do it within the if statement, but do something like?
switch (day.Day) {
case Day.Saturday:
// Do something
break;
}
switch (day.Day) {
case Day.Saturday:
// Do something
break;
}
MODiX
MODiX3y ago
Toshiya Joshima#3472
REPL Result: Success
private enum Days
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
var names = Enum.GetNames<Days>();
var values = Enum.GetValues<Days>().Cast<int>();

var collection = names.Zip(values, (s, days) => (days, s));

Console.WriteLine(string.Join(Environment.NewLine, collection));
private enum Days
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
var names = Enum.GetNames<Days>();
var values = Enum.GetValues<Days>().Cast<int>();

var collection = names.Zip(values, (s, days) => (days, s));

Console.WriteLine(string.Join(Environment.NewLine, collection));
Console Output
(0, Monday)
(1, Tuesday)
(2, Wednesday)
(3, Thursday)
(4, Friday)
(5, Saturday)
(6, Sunday)
(0, Monday)
(1, Tuesday)
(2, Wednesday)
(3, Thursday)
(4, Friday)
(5, Saturday)
(6, Sunday)
Compile: 727.529ms | Execution: 111.930ms | React with ❌ to remove this embed.
Servator
Servator3y ago
you can check index number it's 5 or 6 etc
switch (day.Day) {
case Day.Saturday or Day.Sunday:
// Do something
break;
default:
// Do something else for weekdays
break;
}
switch (day.Day) {
case Day.Saturday or Day.Sunday:
// Do something
break;
default:
// Do something else for weekdays
break;
}
with switch it should be look something like this
CoreVisional
CoreVisionalOP3y ago
Hmm, another reason why I didn't wanna use switch case is because there's a chunk of code under the if body, so moving them inside the case won't look neat.
D.Mentia
D.Mentia3y ago
er... if I'm understanding this right, you're just looking for if (day.Day == Days.Saturday)
CoreVisional
CoreVisionalOP3y ago
No, both values. The above except the post itself were just examples
D.Mentia
D.Mentia3y ago
Then put an or in
CoreVisional
CoreVisionalOP3y ago
Yeah, something like if (Model.State.IsValid && day.Day != Saturday or day.Day != Sunday && day.File != null), I was also hoping if it was possible to just extract the values and assign them to a variable
D.Mentia
D.Mentia3y ago
but really, make a Day[] Weekends = new() { Days.Saturday, Days.Sunday } and check if (Weekends.Contains(day.Day))
CoreVisional
CoreVisionalOP3y ago
I'm assuming this one checks against the values in enum Weekends? Or is it creating a new enum?
D.Mentia
D.Mentia3y ago
It is assuming there is enum Days, and replaces enum Weekends Also I'd rename that variable, day - it's not a Day, day.Day is a Day...
Servator
Servator3y ago
if (day.Day is Days.Saturday or Days.Sunday) is fine too after handling weekends else part is weekdays
CoreVisional
CoreVisionalOP3y ago
Assumes there is enum Days...hmm, so, it is creating a new enum then? If not, I still don't get this part I'm assuming it should be if (day.Day is Days.Saturday or day.Day is Days.Sunday)?
Servator
Servator3y ago
no
CoreVisional
CoreVisionalOP3y ago
Btw, this wouldn't really work as day gets value from user selection. So Weekends.Contains(day.Day)) checks for the value in that enum, when it should be the other way around
D.Mentia
D.Mentia3y ago
The user selects a Day, from enum Days. Weekends is a collection of Days. If the user-selected Day is in Weekends, it's a weekend
CoreVisional
CoreVisionalOP3y ago
Apparently I get errors saying that Day[] cannot be used as a context of type new() Also, Days doesn't exist error as well...
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
CoreVisional
CoreVisionalOP3y ago
Yea but flag is checking for value existence tho, I'm not checking to see if the value exists I'm checking if the selected value is the same as the one in enum. The dropdown value is retrieved from the enum, so in other words, values already exist, just need to check what the user selects Plus, I'm not looking to modify my model class. It seems like Flags requires some modifications to it
hippiewho
hippiewho3y ago
If im understanding correctly you just want to make the expression shorter? Maybe something like
var weekends = Weekends.Saturday | Weekends.Sunday;
bool isWeekEnd = weekends.HasFlag(day.Day);
var weekends = Weekends.Saturday | Weekends.Sunday;
bool isWeekEnd = weekends.HasFlag(day.Day);
CoreVisional
CoreVisionalOP3y ago
Hmm, how about this?
var weekendValues= new[] { Weekends.Saturday, Weekends.Sunday}.Contains(day.Day);
var weekendValues= new[] { Weekends.Saturday, Weekends.Sunday}.Contains(day.Day);
and in my if statement, since I don't want to accept these two values, I just negate like if (!weekendValues). I tried it and it works, but I'm not sure if there's some underlying caveat here Getting error "Type must be an enum that does not have an associated FlagsAttribute. (Parameter 'TEnum')"
hippiewho
hippiewho3y ago
are you using the flags attribute?
CoreVisional
CoreVisionalOP3y ago
Yea, I have [Flags] placed above the public enum
hippiewho
hippiewho3y ago
do you need it? you cant use it if you want to use HasFlag
CoreVisional
CoreVisionalOP3y ago
Does this [Flags] modify anything? Or it's there awaiting for instruction? Like the use of "HasFlag" Because if it does modify, this solution won't work for me, it will disrupt 80+ other references to this enum Ohh, so no need the [Flags] right?
hippiewho
hippiewho3y ago
nope
CoreVisional
CoreVisionalOP3y ago
Hmm, ill try again Didn't work, same error Ohh now it's working, hmm, weird Okay yeah, tested both ways. It works. Cool, two ways of solving it after hours of debugging lol.
hippiewho
hippiewho3y ago
Bitwise ops are a little faster i think but really its negligible. Im curious tho, is the weekends enum new or does it exist in your code base already?
CoreVisional
CoreVisionalOP3y ago
already exist But yeah, I read that HasFlag is best used when values aren't defined Since it's checking for value existence
hippiewho
hippiewho3y ago
I ask because maybe it would be cleaner to do something like
enum Days{
Mon,
Tues,
...,
Saturday,
Sunday,
Weekends = Saturday|Sunday
}
enum Days{
Mon,
Tues,
...,
Saturday,
Sunday,
Weekends = Saturday|Sunday
}
Tho i guess this would create issues if you try to dynamically enumerate the values into a list or somethin
CoreVisional
CoreVisionalOP3y ago
Yeah I didn't wanna use this cuz idk if it will cause some side-effects to the other 80+ classes referencing this class
hippiewho
hippiewho3y ago
yup thats reasonable lol
CoreVisional
CoreVisionalOP3y ago
I'm assuming for this approach, I'd just need to do something like?
var test = Weekends.Weekends;
bool isWeeknd = Weekends.HasFlag(day.Day);
var test = Weekends.Weekends;
bool isWeeknd = Weekends.HasFlag(day.Day);
hippiewho
hippiewho3y ago
Well if you added the Weekends values to Days then all you would need to do is bool isWeeknd = Days.Weekends.HasFlag(day.Day); Assuming day.Day is of enum type Days
CoreVisional
CoreVisionalOP3y ago
Also, I read that HasFlag is used for FlagsAttributes, but somehow it managed to work even without defining the FlagsAttribute? Owhh, okay....that's more cleaner. Still, can't use it without knowing it wouldn't break some other things first. Thanks tho
hippiewho
hippiewho3y ago
The flags attribute should really only be used when the enums values are base 2. ei 0,1,2,4,8,16,etc EDIT: meant powers of 2 The has flag works rgardless because at its core its a bitwise check (IIRC). The flags attribute markes the enum as a powers of 2 flag (under the hood it uses binary flags - 0001, 0010, 0100, 1000, etc)
CoreVisional
CoreVisionalOP3y ago
I'm assuming by default the enum values are base 2 right?
hippiewho
hippiewho3y ago
I honestly dont remember the reasons for the restrictions Actually you got me thinking and so i just tested this out. I was wrong, you would need to make the values of the enum into powers of 2. By default enums are start at 0 get assigned a value +1 greater than the previous. Has flag only works correctly if the values are non zero and power of two. The flags attribute can enforce that rule but HasFlag is part of the enum type and can be used (incorrectly) when the enum is not power of 2
CoreVisional
CoreVisionalOP3y ago
So, that means the values have to be like
public enum Weekends
{
Saturday = 2,
Sunday = 4
}
public enum Weekends
{
Saturday = 2,
Sunday = 4
}
for HasFlag() to work properly? Weird, because I didn't increase the numeric value yet it works accordingly.
Accord
Accord3y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server