简体   繁体   English

如何使您的身材矮一些?

[英]How to make your if shorter?

I understood that when using Regex I can enter the value | 我知道使用正则表达式时,我可以输入| to search for many values. 搜索许多值。 For example: 例如:

Regex sabrina = new Regex("Rihanna|rihanna|Sabrina|sabrina");

I have a string which I want to compare to other values, so I use if like this: 我有一个要与其他值进行比较的字符串,所以我使用if像这样:

if (rihanna == "Rihanna" || rihanna == "sabrina")

My question is if it possible to make the if shorter? 我的问题是是否可以使if缩短? I know this code is not working but what I'm looking for something like this: 我知道这段代码无法正常工作,但是我正在寻找这样的东西:

if (rihanna == "Rihanna|sabrina")

Single line solution: 单线解决方案:

if("Rihanna|rihanna|Sabrina|sabrina".Split(new[] {'|'}).Contains(rihanna))

or without String.Split method usage: 或不使用String.Split方法的用法:

if ((new[] { "Rihanna", "rihanna", "Sabrina", "sabrina" }).Contains(rihanna))

If that kind of check is performed more than once you should save string[] array of possible values into a variable: 如果多次执行此类检查,则应将可能值的string[]数组保存到变量中:

var names = new[] { "Rihanna", "rihanna", "Sabrina", "sabrina" };

if(names.Contains(rihanna))

You could use a List<string> along with the Enumerable.Contains method. 您可以将List<string>Enumerable.Contains方法一起使用。

Example: 例:

var values = new List<string> { "Rihanna", "rihanna", "Sabrina", "sabrina" };

if (values.Contains(rihanna)) 
{
    // etc.
}

The if statement is now a lot more concise, and you can add more items to your list quickly and easily. 现在, if语句更加简洁,您可以轻松快捷地将更多项添加到列表中。 If you're performing this operation frequently, you should move the declaration of the list to a member variable in the containing class so that you don't incur the overhead of list initialization every time this method is called. 如果您经常执行此操作,则应将列表的声明移动到包含类中的成员变量,以免每次调用此方法时都不会产生列表初始化的开销。

An even better solution would be to use Enumerable.Any and String.Equals to perform a case-insensitive comparison: 更好的解决方案是使用Enumerable.AnyString.Equals进行不区分大小写的比较:

if (values.Any(x => String.Equals(rihanna, x, StringComparison.OrdinalIgnoreCase))
{
   // your code here
}

Although the if statement is now longer, the solution is much more robust. 尽管现在if语句更长了,但是该解决方案更加健壮。

If you're looking for easier maintenance of a potentially long list of string candidates, why not use a switch statement? 如果您希望更容易地维护可能很长的字符串候选列表,为什么不使用switch语句? Technically it will be "longer" character-wise, but if you have to modify things down the road, or provide some subtle secondary processing, it could make things a lot easier. 从技术上讲,它将是“更长”的字符,但是,如果您必须在将来进行修改或提供一些细微的辅助处理,则可以使事情变得容易得多。

As an alternative to the above answers, perhaps you could consider using an extension method: 作为上述答案的替代方法,也许您可​​以考虑使用扩展方法:

public static bool EqualsAny(this string input, params string[] values)
{
    return values.Any(v => String.Equals(input, v, StringComparison.OrdinalIgnoreCase));
}

With usage like: 用法如下:

if (rihanna.EqualsAny("Rihanna", "Sabrina"))

This should give pretty readable/compact/short if comparisons for you, especially in comparison to some of the other alternatives here. if您进行比较,这应该会提供相当可读/紧凑/简短的注释,尤其是与此处的其他一些替代方法相比。

Tweak the EqualsAny check if you want to have the OrdinalIgnoreCase or not or feel free to add any overloads you wish. 调整EqualsAny检查,是否要使用OrdinalIgnoreCase或随意添加所需的重载。 Could even implement the whole piping/splitting where you'd pass in "Rihanna|Sabrina". 甚至可以实现您在“蕾哈娜(Rihanna | Sabrina)”中通过的整个管道/拆分。

EDIT: Perhaps more critically, it centralizes how you compare rather than duplicating the code everywhere. 编辑:也许更关键的是,它集中您进行比较的方式,而不是在各处复制代码。

You can use your own Regex and use it as a single line.. 您可以使用自己的Regex并将其用作一行。

if (Regex.Match(rihanna, "Rihanna|rihanna|Sabrina|sabrina").Success)

Or make it case-insensative like this.. 或者像这样使它不区分大小写。

if (Regex.Match(rihanna, "rihanna|sabrina", RegexOptions.IgnoreCase).Success){

Ignore casing, which looks like something you're going for, and use String.Compare : 忽略看起来像您要使用的String.Compare ,并使用String.Compare

if(String.Compare(rihanna, "sabrina", StringComparison.OrdinalIgnoreCase) == 0 ||
   String.Compare(rihanna, "rihana", StringComparison.OrdinalIgnoreCase) == 0 ) {
    // do stuff
}

Dictionary or HashSet (potentially with case insensitive check on names) is another approach which will give you better performance if you have more than several items and repeat checks often. DictionaryHashSet (可能对名称进行不区分大小写的检查)是另一种方法,如果您有多个项目并且经常重复检查,则可以提供更好的性能。

 var listToCheck = new Dictionary<string, string>( 
     StringComparer.CurrentCultureIgnoreCase) { { "rihanna", null}};

 if (listToCheck.ContainsKey("Rihanna")) ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM