【问题标题】:How to print every data row except for one in C#如何在C#中打印除一个之外的每个数据行
【发布时间】:2014-03-28 15:06:23
【问题描述】:

我有一个 for 循环来打印一组地址。但我想做一个条件,它跳过打印与 postalCode-X 具有相同值的地址集。

那么我怎样才能从 forloop 中逃脱呢? 该语言采用 C#、.NET 框架。谢谢。

数据看起来像这样:

SET 1 
Street 1
California 1770 

SET 2 
Street 2 
New Jersey 1990 

SET 3 
Street 3 
Oakland 2000

邮政编码 1990 除外的输出:

仅打印 SET1 和 SET3。

foreach (Dataset.Row dr in A.Rows)
        {
            if (dr.id("1"))
            {
                string unit = dr.unit;
                string streetName = dr.street;
                string postalCode = dr.postal;
                content += String.Format("{0}", dr.name);
                if (showAddress)
                    content += "<br/>" + GenAddr(unit,streetName, postalCode) + "<br/>";
            }
        }

【问题讨论】:

  • 感谢您更新代码。为什么你有if(dr.id("1"))?我现在认为您不想打印到控制台,但您想将 HTML 内容写入客户端。什么是内容?
  • 嗨,dr.id('1') 只是一个例子,它实际上是指一个类型为 A 的列,然后进入该 if 语句。内容将生成为word文档。也可以说是HTML。

标签: c# asp.net .net for-loop


【解决方案1】:
//inside the loop
if(!currentset.PostalCode.Equals("1990"))
    {
    Console.WriteLine("Set: "+currentset);
    }

一个简单的 if 语句就可以满足您的需求。如果您使用循环更新问题以及集合是什么数据类型等,我可以为您提供更适合您情况的答案。

请注意,上面的代码不是“转义”循环。它只是有选择地从 for 循环内部打印出集合。下面的代码利用 C# 中的 continue 语句来“转义”循环中的其余代码。

//inside the loop
if(currentset.PostalCode.Equals("1990")
{
    continue; //the curly braces are unnecessary for a single line in the if statement
}
Console.WriteLine("Set: "+currentset); //notice this is after the continue statement

另一种选择是在有一个打印出集合的循环之前先有 List,然后是 remove the sets with Linq

List<set> sets=GetSets();
set.RemoveAll(aset => aset.PostalCode.Equals("1990"));
//now loop through sets
foreach(set currentset in sets)
{
    Console.WriteLine("Set: "+set);
}

【讨论】:

    【解决方案2】:

    或者使用 linq。

    yourList.Where(x=>!x.PostalCode.Equals("1990")).ForEach(Console.WriteLine)
    

    【讨论】:

      【解决方案3】:

      你还有别的办法:

      //inside the loop
      if(!currentset.PostalCode.Equals("1990"))
      {
          Console.WriteLine("Set: "+currentset);
      }
      

      //inside the loop
      if(currentset.PostalCode.Equals("1990"))
          continue;
      Console.WriteLine("Set: "+currentset);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        • 1970-01-01
        • 2021-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多