问题
I have this piece of code:
if (filter != RECENT &&
filter != TODAY &&
filter != WEEK &&
filter != MONTH &&
filter != ALLTIME)
{
filter = RECENT;
}
Note that filter
is a string
and it's compared against const string
types. Is there any way to do this inline and have it be more readable? Doing it with the ternary operator doesn't make it much better since I still have to repeat filter != XXXXX
filter = filter != RECENT &&
filter != TODAY &&
filter != WEEK &&
filter != MONTH &&
filter != ALLTIME ? RECENT : filter;
and this clearly doesn't work
filter = filter != RECENT && TODAY && WEEK && MONTH && ALLTIME ? RECENT : filter;
Is there any prettier way (prettier == all of the logic must be in a single line of code) to do this comparison? More specifically to prevent filter != XXXXX
repetition.
Note that performance is not my primary concern for this question.
回答1:
I Prefer create an extension method .
public static bool NotIn(this string filter , params string[] valuesToCompare)
{
var result = true;
foreach (var item in valuesToCompare)
{
if (filter == item) return false;
}
return result;
}
and use like
if( filter.NotIn("RECENT", "TODAY ", "WEEK ", "MONTH", "ALLTIME"))
{
filter = "RECENT";
}
回答2:
Note this answer was written before the OP clarified that they wanted only single line solutions.
Using an HashSet
Case-sensitive comparison:
var filters = new HashSet<string>(new[] { RECENT, TODAY, WEEK, MONTH, ALLTIME });
if (!filters.Contains(filter))
{
filter = RECENT;
}
Case-insensitive comparison:
var filters = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
filters.UnionWith(new[] { RECENT, TODAY, WEEK, MONTH, ALLTIME });
if (!filters.Contains(filter))
{
filter = RECENT;
}
Using an array of strings
Case-sensitive comparison:
string[] filters = {RECENT, TODAY, WEEK, MONTH, ALLTIME};
if (!filters.Contains(filter))
{
filter = RECENT;
}
Case-insensitive comparison:
string[] filters = {RECENT, TODAY, WEEK, MONTH, ALLTIME};
if (!filters.Contains(filter, StringComparer.OrdinalIgnoreCase))
{
filter = RECENT;
}
EDIT
The ternary operator ?:
could be used instead of the if
statement, but IMO that would make the code less readable. Also, from a debugging perspective, it's easier to set a breakpoint inside the if
statement to check if the array contains the filter, as opposed to setting the breakpoint using the operator ?:
:
来源:https://stackoverflow.com/questions/53020921/c-sharp-prettier-way-to-compare-one-value-against-multiple-values-in-a-single