C# linq检查字符串值
是否有更好的方法使用Linq编写以下内容 需要检查bool返回的值是否为true和falseC# linq检查字符串值,c#,c#-4.0,c#-3.0,C#,C# 4.0,C# 3.0,是否有更好的方法使用Linq编写以下内容 需要检查bool返回的值是否为true和false string checkvalue = nodeIterator.Current.Value.ToString(); if (checkvalue == "true") { taxSpecification = 3; } else if (checkvalue == "false") { taxSpecification = 3; } 您可以解析字符串以返回布尔值: bool myBo
string checkvalue = nodeIterator.Current.Value.ToString();
if (checkvalue == "true")
{
taxSpecification = 3;
}
else if (checkvalue == "false")
{
taxSpecification = 3;
}
您可以解析字符串以返回布尔值:
bool myBool;
if (!bool.TryParse(checkvalue, out myBool)
throw new Exception("This is not a valid bool");
...
如果需要更通用的方法(即字符串可能不是有效的TryParse值):
这并不能真正解决Linq部分,但可以在循环体中有所帮助。试试这个
var checkvalue = "false";
bool myRes = false;
int tax = 0;
if (bool.TryParse(checkvalue, out myRes))
{
tax = (myRes) ? 3 : 4;
}
没有Linq,但您可以将其编写为
if (checkvalue == "true" || checkvalue == "false")
{
taxSpecification = 3;
}else
{
// wrong input
}
当一个简单的.NET2.0逻辑就足够的时候,为什么要使用LINQ或一些奇特的东西呢
switch (nodeIterator.Current.Value.ToString())
{
case "true":
case "false":
taxSpecification = 3;
break;
}
总是很糟糕吗?我的意思是,唯一可以接受的值是“真”和“假”,taxSpecification真的总是3吗?您的代码读起来很好,但是您可以使用三元/条件(?:)运算符,例如,如果您想减少代码行数。您确定nodeIterator.Current.Value将始终为非null吗?如果我们能看到您正在迭代的结构,Linq会更有帮助。实际上,它是典型的,不是吗。无论发生什么,税收都是不变的;-)LINQ不是你应该撒在所有代码上的魔法精灵。专注于正确的逻辑。@dash-除非你是吉米·卡尔(为我们的英国读者)。
switch (nodeIterator.Current.Value.ToString())
{
case "true":
case "false":
taxSpecification = 3;
break;
}