【问题标题】:C# if else conditional inside of foreach loop possibly using countC# if else 条件在 foreach 循环内可能使用计数
【发布时间】:2020-11-18 11:54:25
【问题描述】:

我在这里有没有条件的工作示例。

public string RenderPostTags(DMCResultSet resultSet)
{
    string output = "";
    string filterForm = RenderFilterForm(resultSet);
    string pagination = RenderPagination(resultSet);
    List<XElement> items = resultSet.items;
    foreach(XElement i in items)
    {
        string tags = "";
        if (i.Element("tags") != null) 
        {
            foreach(string tag in i.Element("tags").Elements("tag"))
            {
                tags += "<a href=\"?tag=" + HttpUtility.UrlEncode(tag) + "\">" + tag + "</a>"; 
            }
        }
        output += tags;
    }
    return  output;
}

我知道仅仅依靠它是行不通的,但我尝试了几种不同的方法,但它们对我没有用。可能是语法错误我是个 C# 菜鸟。

但我需要使用类似于此的 if else 条件输出调整后的 html

public string RenderPostTags(DMCResultSet resultSet){
            string output = "";
            string filterForm = RenderFilterForm(resultSet);
            string pagination = RenderPagination(resultSet);
            List<XElement> items = resultSet.items;
            foreach(XElement i in items){
                string tags = "";
                if (i.Element("tags") != null) {
                    int count = 1;
                    int total = i.Element("tags").Elements("tag").Count;
                    foreach(string tag in i.Element("tags").Elements("tag")) {
                        if(count == total){
                            tags += "<a href=\"?tag=" + HttpUtility.UrlEncode(tag) + "\">" + tag + "</a>"; 
                            count++;
                        }else{
                            tags += "<a href=\"?tag=" + HttpUtility.UrlEncode(tag) + "\">" + tag +","+ " " + "</a>";  
                            count++;
                        }
                    }
                }
                output += tags;
            }
            return  output;
        }

我尝试过的方法可以在这个帖子上找到。 Foreach loop, determine which is the last iteration of the loop

感谢您的帮助。

【问题讨论】:

  • 当不在循环的最后一次交互时,我需要在我的 HTML 输出中添加空格和逗号。问题是我在迭代最终项目时难以设置监控机制。希望有帮助
  • counter 不会改变,除非你放 counter++;在 foreach 循环内。
  • 您是否要在循环中获取计数?如果是这样,为什么不使用旧的 for 循环?
  • 好的,所以在循环外声明一个count变量并将其设置为1。通过var total = items.Count()获取循环外项目的总数。然后在每次迭代的循环内将计数增加 1,请参阅if(count == total)
  • 好的,我已经继续并更新了上面的代码以使其可读。感谢您迄今为止的帮助。

标签: c#


【解决方案1】:

所以也许出于命名空间的原因,count 方法不能解决我的问题。 然而,经过一番努力,这个解决方案完美地工作了。感谢那些帮助我找到这个解决方案的人。

public string RenderPostTags(DMCResultSet resultSet){
            string output = "";
            string filterForm = RenderFilterForm(resultSet);
            string pagination = RenderPagination(resultSet);
            List<XElement> items = resultSet.items;

            foreach(XElement i in items){
                string tags = "";
                if (i.Element("tags") != null) {
                    foreach(string tag in i.Element("tags").Elements("tag")){
                        if(tags != "") tags += ", &nbsp; ";
                        tags += "<a href=\"?tag=" + HttpUtility.UrlEncode(tag) + "\">" + tag  +"</a>"; 
                    }
                }
                output += tags;
            }
            return  output;
        }

【讨论】:

    【解决方案2】:

    您可以像这样编写 foreach 循环来捕获这两个条件。您可以使用condition ? true : false 来编写/或基于集合中的最后一项。

    int counter = 1; // Start with 1 since we are using != later on.
    int totalRecords = i.Element("tags").Elements("tag").Count();
    foreach (string tag in i.Element("tags").Elements("tag"))
        tags += "<a href=\"?tag=" + HttpUtility.UrlEncode(tag) + "\">" + tag + counter++ != totalRecords ? ", "  : string.Empty + "</a>";
    

    以上等价于

    if (i.Element("tags") != null)
    {
        int counter = 1;
        int totalRecords = i.Element("tags").Elements("tag").Count();
        foreach (string tag in i.Element("tags").Elements("tag"))
        {
            if (counter++ == totalRecords)
            {
                tags += "<a href=\"?tag=" + HttpUtility.UrlEncode(tag) + "\">" + tag + "</a>";
            }
            else
            {
                tags += "<a href=\"?tag=" + HttpUtility.UrlEncode(tag) + "\">" + tag + ", " + "</a>";
            }
        }
    }
    

    记下IEnumerable 没有Count 属性,但有一个方法Count()

    【讨论】:

      【解决方案3】:

      正如@Sach 所说,使用 for 循环而不是 foreach。

      string output = "";
      List<XElement> items = new List<XElement>();
      foreach (XElement i in items)
      {    
          string tags = "";
          if (i.Element("tags") != null && i.Element("tags")?.Elements("tag") != null)
          {
              List<XElement> tagItems = i.Element("tags").Elements("tag").ToList();
              if (tagItems == null) continue;
              for (int j = 0; j < tagItems.Count(); j++)
              {
                  XElement tag = tagItems[j];
                  if (j == i.Element("tags")?.Elements("tag").Count() - 1)
                  {
                      tags += "<a href=\"?tag=" + HttpUtility.UrlEncode(tag) + "\">" + tag + "</a>";
                  }
                  else
                  {
                     tags += "<a href=\"?tag=" + HttpUtility.UrlEncode(tag) + "\">" + tag + "," + " " + "</a>";
                  }
              }
          }
          output += tags;
      }
      

      【讨论】:

        猜你喜欢
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 2019-10-09
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 2016-07-11
        • 2012-09-02
        相关资源
        最近更新 更多