简体   繁体   English

如何简化 C# 中的大 if 语句?

[英]How to simplify a big if statement in C#?

Current in my code, if statement is too big and many repetitions.当前在我的代码中,if 语句太大且重复很多。

if (!String.Equals(node.Name, "A", StringComparison.OrdinalIgnoreCase)
 && !String.Equals(node.Name, "B", StringComparison.OrdinalIgnoreCase)
 && !String.Equals(node.Name, "C", StringComparison.OrdinalIgnoreCase)
 &&  ... 

I would like to make it concise.我想让它简洁。 But my idea is only to create a function and passing List or Array as param.但我的想法只是创建一个函数并将 List 或 Array 作为参数传递。

List<String> target = new List<String>() { "A", "B", "C" ... };
MultipleStringCompare(node.Name, target, , StringComparison.OrdinalIgnoreCase);

Is there any more beautiful way to make it simple without making any function in modern C# syntax?有没有更漂亮的方法来使它简单而不用现代 C# 语法创建任何函数?

The fastest will be a HashSet<string> .最快的将是HashSet<string> This becomes more evident as you get into the hundreds or thousands or more of strings to compare against.当您进入成百上千或更多的字符串进行比较时,这一点变得更加明显。 Think a list of profane words, or a list of customer email addresses, etc. Unlike a one-off LINQ query with a temporary list or array, the set you create will be queried super fast and can be mutated if you desire to add even more words at runtime if you want.想想亵渎词的列表,或客户电子邮件地址的列表等。 与具有临时列表或数组的一次性 LINQ 查询不同,您创建的集合将被超快地查询,如果您想添加甚至可以改变如果需要,可以在运行时使用更多单词。 You could wrap this in a function, but doing a strings.Contains(...) is so easy it may not be worth it.你可以把它包装在一个函数中,但是做一个strings.Contains(...)太容易了,可能不值得。

The following snippet also takes care of making every comparison case-insensitive so you don't have to think about it every time you do a string compare.以下代码段还负责使每个比较不区分大小写,因此您不必在每次进行字符串比较时都考虑它。

// create a fast lookup for strings using a case-insensitive set
HashSet<string> strings = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "A", "B", "C", "D" };
if (strings.Contains(node.Name))
{
    // string exists, do logic...
}

// later you can add or remove strings if you want...
// strings.Add("E");
// strings.Remove("A");

Yep, there's a way to do that using LINQ's functions.是的,有一种方法可以使用 LINQ 的函数来做到这一点。

The All function checks if all elements match the condition. All函数检查是否所有元素都符合条件。

The Any function checks if at least one element matches the condition. Any函数检查是否至少有一个元素与条件匹配。

So in your case, your code will look like this所以在你的情况下,你的代码看起来像这样

var result = !target.Any(str => string.Equals(node.Name, str, StringComparison.OrdinalIgnoreCase));

You can use a LINQ statement:您可以使用 LINQ 语句:

string[] comparisons = { "A", "B", "C" ... };
bool noMatch = comparisons.All(n => !String.Equals(node.Name, n, StringComparison.OrdinalIgnoreCase));

If noMatch is true, this is equivalent to your if statement being true.如果noMatch为真,则相当于您的if语句为真。 This assumes the strings you're comparing to are in the comparisons array.这假设您要比较的字符串在comparisons数组中。

How this works:这是如何工作的:

.All() is a LINQ extension method that takes a predicate as an input. .All()是一种将谓词作为输入的 LINQ 扩展方法。 This function will return true if the passed predicate returns true for every iteration.如果传递的谓词在每次迭代中都返回true则此函数将返回true The predicate takes a single string and returns a boolean.谓词采用单个字符串并返回一个布尔值。 So this is effectively equivalent to:所以这实际上等效于:

bool noMatch = true;
foreach (string n in comparisons)
{
    if (!String.Equals(node.Name, n, StringComparison.OrdinalIgnoreCase))
        continue;
    noMatch = false;
    break;
}

You can use the Any method in LINQ:您可以在 LINQ 中使用Any方法:

string s = "A";
!(new List<string> { "A", "B", "C", "D" }).Any(x => String.Equals(x, s, StringComparison.OrdinalIgnoreCase)

You can do:你可以做:

var toAvoid = new []{"A", "B", "C"};
var isNameNotInToAvoid = !toAvoid.Contains(node.Name,
    StringComparer.InvariantCultureIgnoreCase);

if(isNameNotInToAvoid)

Probably simplest:可能最简单:

if ("ABCDEFG".Contains(node.Name.ToUpper()))
    ;// things to do if node.Name is in string "ABCDEFG"

or, in case of not only single characters comparison:或者,如果不仅是单个字符比较:

if ("AB|CDE|F|G|HIJK|L".Split('|').Any(c => String.Equals(node.Name, c.ToString(), StringComparison.OrdinalIgnoreCase)))
    ;// things to do if node.Name is one of "AB", "CDE", "F", "G", "HIJK", "L"

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

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