【问题标题】:Store list values in a string in c#在c#中将列表值存储在字符串中
【发布时间】:2016-12-16 05:43:00
【问题描述】:

我有一个存储一些字符串值的列表。

代码:

List<VBCode> vbCodes = new List<VBCode>();

public class VBCode
{
    public string Formula { get; set; }
}

在我试图附加列表值的方法中。

public void ListValue()
  {
    if (vbCodes.Count > 0)
      {
         StringBuilder strBuilder = new StringBuilder();
         foreach (var item in vbCodes)
           {
             strBuilder.Append(item).Append(" || ");
           }
         string strFuntionResult = strBuilder.ToString();
      }
   }

该列表将具有如下所示的值

如何获取公式值并附加到 foreach 中?

【问题讨论】:

    标签: c# asp.net .net c#-4.0


    【解决方案1】:

    您将需要的item object 附加到append object property Formula

    public void ListValue()
      {
        if (vbCodes.Count > 0)
          {
             StringBuilder strBuilder = new StringBuilder();
             foreach (var item in vbCodes)
               {
                 strBuilder.Append(item.Formula).Append(" || ");
               }
             string strFuntionResult = strBuilder.ToString();
          }
       }
    

    【讨论】:

      【解决方案2】:

      你可以在没有foreach的情况下使用String.Join()简单地做到这一点,它会是这样的:

       string strFuntionResult = String.Join(" || ", vbCodes.Select(x=>x.Formula).ToList());
      

      如果您真的想使用 foreach 进行迭代,则意味着您必须从迭代器变量中获取 Formula,还要注意在完成迭代后删除最终的 ||,如果是这样,代码将如下所示:

      StringBuilder strBuilder = new StringBuilder();
      foreach (var item in vbCodes)
      {
          strBuilder.Append(item.Formula).Append(" || ");
      }
      string strFuntionResult = strBuilder.ToString(); // extra || will be at the end
      // To remove that you have to Trim those characters 
      // or take substring till that
      strFuntionResult = strFuntionResult.Substring(0, strFuntionResult.LastIndexOf('|')); 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-22
        • 2022-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多