[英]Simplify an if statement with a method C#
I was wondering if there is any possible way to simplify this.我想知道是否有任何可能的方法来简化这一点。
if (string != "")
{
dataGridView1.Rows.Add(string);
}
All I can find is how to shorten if statements which return a value, not execute a method like mine.我能找到的只是如何缩短返回值的 if 语句,而不是执行像我这样的方法。
There is not much to do from where you are already.从你现在的位置没有什么可做的。 I would only suggest inverting the if statement to reduce nesting.我只建议反转 if 语句以减少嵌套。 You could also remove the braces by using this method like this:您还可以使用以下方法删除大括号:
if (string == "") return;
dataGridView1.Rows.Add(string);
If you want to check if a string is not empty and then add it to your dataGridView1.Rows at multiple places in your code, you could declare an Action<string> like如果要检查字符串是否不为空,然后将其添加到代码中多个位置的 dataGridView1.Rows 中,则可以声明 Action<string> 之类的
Action<string> AddRowIfInputNotEmpty = new Action<string>(input =>
{
if (!string.IsNullOrEmpty(input))
dataGridView1.Rows.Add(input);
});
And then call it like AddRowIfInputNotEmpty.Invoke("MyString");
然后像AddRowIfInputNotEmpty.Invoke("MyString");
whenever you need it每当你需要它
Create an extension method AddIfNotEmpty
for DataGridViewRowCollection
:为DataGridViewRowCollection
创建扩展方法AddIfNotEmpty
:
public static void AddIfNotEmpty(this DataGridViewRowCollection rows, string value)
{
if(!string.IsNullOrEmpty(value))
rows.Add(value);
}
Usage:用法:
dataGridView1.Rows.AddIfNotEmpty(stringValue);
Since Add method returns an int you can simplify (uglify if you ask me) using the discards operator:由于 Add 方法返回一个 int ,因此您可以使用 discards 运算符进行简化(如果您问我就丑化):
_ = yourString != "" ? dataGridView1.Rows.Add(yourString) : 0;
Or as Jeremy Pointed out:或者正如杰里米指出的那样:
_ = !string.IsNullOrEmpty(yourString) ? Add(list, yourString) : 0;
(As a note, when checking the equality of a string, you should use stringVar.equals()
Also, when looking for null or whitespace data, you can use stringVar.IsNullOrWhiteSpace()
) (注意,在检查字符串的相等性时,您应该使用stringVar.equals()
另外,在查找空或空白数据时,您可以使用stringVar.IsNullOrWhiteSpace()
)
Well, you can try嗯,你可以试试
//Note: I haven't tested this and you may need to fiddle it a bit
if(!String.IsNullOrWhiteSpace(stringVar)) dataGridView1.Rows.Add(stringVar);
//you can also use something like this
!String.IsNullOrWhiteSpace(stringVar) ? //if true : //if false;
Let me know if this doesn't satisfy your question and I will attempt to amend my statements.如果这不能满足您的问题,请告诉我,我将尝试修改我的陈述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.