【问题标题】:Conditional string formatting条件字符串格式
【发布时间】:2013-07-07 04:30:27
【问题描述】:

我正在尝试使用条件字符串格式来显示找到或不这样的记录 “找到 10 行中的 5 行”

string msg = "{0:#;;} of {1:#;;} {2:rows;no rows;row} found";
return string.Format(msg, searchItems, totalItems, totalItems - 1);

在 totalItems 为 0 之前一切正常,因为我得到了这样的消息集。 “未找到行”(错误)

我想要这样的东西 “没有找到行”

searchItems = 0 ; totalItems = 0 ==> "no rows found"

searchItems = 1 ; totalItems = 1 ==> "1 row found"

searchItems = 2 ; totalItems = 5 ==> "2 of 5 rows found"

【问题讨论】:

    标签: c# string conditional string.format


    【解决方案1】:

    您可以在searchItems 变量中添加一个.ToString(),例如:

    string msg = "{0:#;;} of {1:#;;} {2:rows;no rows;row} found";
    return string.Format(msg, searchItems.ToString(), totalItems, totalItems - 1);
    

    假设searchItemstotalItems 都是0

    0 未找到行

    假设searchItemstotalItems 都是1

    找到 1 行中的 1 行

    假设searchItems2totalItems5

    找到 5 行中的 2 行

    但是,我会重写它并使用 if 语句,这可能是更多的代码行,但更具可读性。

    【讨论】:

    • 我真的很想在没有行的情况下使用这样的东西:“找不到行”多于“没有找到行的 0”,但它确实解决了我的问题。非常感谢!
    猜你喜欢
    • 2014-02-24
    • 2017-04-20
    • 2020-05-02
    • 2016-03-01
    • 2021-03-30
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多