我正在寻找在循环中创建与另一个字符串分隔的字符串的最佳方法.我的意思是,例如,SQL阅读器:
StringBuilder sb = new StringBuilder(); while(reader.Read()) { sb.Append(reader[0]); sb.Append("
"); } string result = sb.ToString(); result = result.Remove(result.LastIndexOf("
")); // <-
或创建SQL查询字符串;
StringBuilder sb = new StringBuilder(); foreach(string v in values) { sb.Append(v); sb.Append(","); } string query = sb.ToString() query = query.Remove(query.LastIndexOf(",")); // <- query = String.Concat("INSERT INTO [foo] ([bar]) VALUES(", query, ")");
这是我发现的最好的:
Listlist = new List ; while(reader.Read()) { list.Add(reader[0]); } string result = String.Join("
", list.ToArray());
编辑: 我知道.我的一般想法不使用StringBuilder
,我没有在这里使用它只是为了清楚Remove
/ LastIndexOf
!
我不是StringBuilder的粉丝,除非你真的知道你需要担心性能.它产生丑陋的代码.我会这样写的......
private IEnumerableReadAllStrings(DataReader reader) { while(reader.Read()) yield return reader[0]; } String.Join("
", ReadAllStrings(reader).ToArray());
如果我做了很多,我可能会考虑一种扩展方法:
public static class Extensions { public static string JoinWith(this IEnumerablestrings, string separator) { return String.Join(separator, strings.ToArray()); } }
然后,我的代码看起来像这样:
ReadAllStrings(reader).JoinWith("
");
怎么样:
StringBuilder builder; while (reader.Read()) { if( builder == null ) { builder = new StringBuilder(reader[0]); } else { builder.Append("
"); builder.Append(reader[0]); } } string result = builder.ToString();