2016-12-16 31 views
0

私はいくつかの文字列値を格納するリストを持っています。リストの値を文字列に格納するC#

コード:私はリスト値を追加しようとしています方法で

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

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

enter image description here

どのように私は式の値を取得し、foreachの中に追加することができ、以下に示すよう

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

リストが値を持っているのだろうか?

答えて

3

あなたはitem objectあなたはあなたがString.Join()を使用することにより、単にforeachせずにこれを行うことができます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(); 
     } 
    } 
3

appendする必要があり、それはこのようになります追加されています。あなたが本当にしたい場合は

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('|')); 
関連する問題