【问题标题】:if statement inside a for loop?for循环中的if语句?
【发布时间】:2016-03-16 20:05:46
【问题描述】:

我有 sql 背景,正在学习 c#。现在我有一个在 x.ph.company、x.ph.product、x.ph.productID 等列上运行的 for 循环(所有制表符分隔)

我想在 x.product 上运行一个 if 语句,其效果是“如果 x.product 包含“未指定的产品”,则返回“未指定的技术”。这是我到目前为止所得到的,但我可以'不完全正确。任何帮助表示赞赏!

String OutputCustomer;
foreach (var x in rs_product_hit)
{
OutputCustomer = String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\r\n"
, x.ph.hit_id
, SetAsSpace(x.ph.url)
, SetAsSpace(x.ph.company)
, SetAsSpace(x.ph.City)
, SetAsSpace(x.ph.State)
, SetAsSpace(x.ph.iso)
, SetAsSpace(x.ph.vendor)
, SetAsSpace(x.ph.product)
if ( x.ph.product == "Unspecified Product" )
{
   x.ph.product = "Unspecified Tech"
}

【问题讨论】:

  • 把它移到一个局部变量中。
  • 你看过c#中的.Contains()函数吗? msdn.microsoft.com/en-us/library/dy85x1sa(v=vs.110).aspx
  • 你能提供你所有的代码吗?
  • 如果 x.product 包含“未指定的产品”,你想返回什么?无论哪种情况,您仍要返回制表符分隔的字符串吗?
  • 请注意,它在for 循环中的事实是无关紧要的。事实上,它位于另一个 statement (String.Format) 中,阻止您使用 if

标签: c# if-statement for-loop


【解决方案1】:

你可以用三元语法做到这一点吗?还有很多其他方法,但对我来说,这似乎最接近您已经在做的事情。

    String OutputCustomer;
    foreach (var x in rs_product_hit)
    {
       OutputCustomer = String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\r\n"
                                    , x.ph.hit_id
                                    , SetAsSpace(x.ph.url)
                                    , SetAsSpace(x.ph.company)
                                    , SetAsSpace(x.ph.City)
                                    , SetAsSpace(x.ph.State)
                                    , SetAsSpace(x.ph.iso)
                                    , SetAsSpace(x.ph.vendor)
                                    , SetAsSpace(x.ph.product)
                                    ,x.ph.product == "Unspecified Product" ?
                                     "Unspecified Tech" : x.ph.product);
    }

【讨论】:

    猜你喜欢
    • 2016-06-16
    • 2019-06-09
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    相关资源
    最近更新 更多