C# - Prettier way to compare one value against multiple values in a single line of code [duplicate]

*爱你&永不变心* 提交于 2020-01-07 09:38:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!