用于检查'if'语句中的多个条件的语法

时间:2012-12-28 09:08:40

标签: c#

这是情况:

if count items is either 0,1,5,7,8,9,10 then string = "string one"
if count items is either 2,3,4 then string = "string two"

我尝试过(在cs razor视图内)

@if (@item.TotalImages == 1 || 5 || 7 || 8 || 9 || 10)
{
   string mystring = "string one"
}

但是我收到了这个错误

  

运营商||不能应用于bool或int

类型的操作数

7 个答案:

答案 0 :(得分:7)

or operator 的语法错误。

更改为。

@if (@item.TotalImages == 1 || @item.TotalImages == 5)
{
   string mystring = "string one"
}

答案 1 :(得分:6)

或者

var accepted = new HashSet<int>(new[] {1, 5, 7, 8, 9, 10});

@if (accepted.Contains(item.TotalImages))
{
   string mystring = "string one"
}

答案 2 :(得分:4)

对于这种情况,In扩展方法可能是语法糖:

public static class CLRExtensions
{
    public static bool In<T>(this T source, params T[] list)
    {
        return list.Contains(source);
    }
}

所以基本上不是使用多个or operator,而是简单地写:

@if (@item.TotalImages.In(1, 5, 7, 8, 9, 10)
{
}

答案 3 :(得分:3)

仔细查看错误消息:

  

运营商||不能应用于 bool int

类型的操作数

你的代码:

@if (@item.TotalImages == 1 || 5)

你正在应用||操作符为bool(@ item.TotalImages == 1)和int(5)。 '真或5'没有意义。也不是'假或5'

基本上,你需要做的就是制作||的两面操作员布尔。

@if (@item.TotalImages == 1 || @item.TotalImages == 5)

当然还有很多其他聪明的方法可以做到这一点,但这可能是最直接的。

答案 4 :(得分:1)

如果你想检查所有这些可能性,你可能会得到一个非常大的'if'语句。使用LINQ执行此操作的更简单方法是:

@if ((new List<int>{ 0, 1, 5, 7, 8, 9, 10 }).Contains(@item.TotalImages))
{
    string mystring = "string one"
}

通过这种方式,您可以更轻松地查看和维护要检查的数字列表(或者确实从其他地方传递它们)。

答案 5 :(得分:0)

我使用开关:

@switch (@item.TotalImages)
{
    case 0:
    case 1:
    case 5:
    case 7:
    case 8:
    case 9:
    case 10:
        s = "string one";
        break;
    case 2:
    case 3:
    case 4:
        s = "string two";
        break;
    default:
        throw new Exception("Unexpected image count");
}

奇怪的是,没有人建议过字典:

private string stringOne = "string one";
private string stringTwo = "string two";

private Dictionary<int, string> _map = new Dictionary<int, string>
{
    { 0, stringOne },
    { 1, stringOne },
    { 2, stringTwo },
    { 3, stringTwo },
    { 4, stringTwo },
    { 5, stringOne },
    { 7, stringOne },
    { 8, stringOne },
    { 9, stringOne },
    { 10, stringOne },
}

然后

@var s = _map[@item.TotalImages];

这种方法可以让您更容易看到,例如,您没有处理TotalImages == 6的情况。

答案 6 :(得分:0)

在“||”之间始终必须是一个表达式,可以转换为布尔值(true / false):

@if (@item.TotalImages == 1 || @item.TotalImages == 5 || @item.TotalImages == 7 || @item.TotalImages == 8 || @item.TotalImages == 9 || @item.TotalImages == 10)
    {
       string mystring = "string one"
    }
@else @if(@item.TotalImages == 2 || @item.TotalImages == 3 || @item.TotalImages == 4)
    {
       string mystirng = "string two"
    }