将结构化List转换为String

时间:2014-11-20 09:06:00

标签: c# c#-3.0

我想将列表转换为字符串而不使用linq库(。Net 3.0)。

我的清单:

class child
{
     public string ObjectName { get; set; }
     public string ColorName { get; set; }
}

 List<child> list = new List<child>();

 list.Add(new child { ObjectName = "Value1", ColorName = "Value3" });
 list.Add(new child { ObjectName = "Value4", ColorName = "Value4" });

得到这样的结果:

String.Concat(list.Select(o => o.ObjectName + "~" + o.ColorName + "~"));

2 个答案:

答案 0 :(得分:3)

您可以使用StringBuilder

var sb = new StringBuilder();

foreach(var c in list)
     sb.Append(c.ObjectName + "~" + c.ColorName + "~");

var result = sb.ToString();

答案 1 :(得分:3)

您可以StringBuilder使用AppendFormat

StringBuilder sb = new StringBuilder();
foreach (child ch in list)
    sb.AppendFormat("{0}~{1}~", ch.ObjectName, ch.ColorName);
string result = sb.ToString();  // Value1~Value3~Value4~Value4~