注意到一些代码,例如
string[] ary = parms.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
for( int i = 0; i < ary.Length; i++)
ary[i] = ary[i].Trim();
工作正常,但想知道是否有更好的方法一步完成
答案 0 :(得分:17)
string[] trimmedStrings = parms.Split(',')
.Select(s => s.Trim())
.Where(s => s != String.Empty)
.ToArray();
BTW,请考虑使用类似List<string>
的通用类型列表而不是传统数组
IList<string> trimmedStrings = parms.Split(',')
.Select(s => s.Trim())
.Where(s => s != String.Empty)
.ToList();
答案 1 :(得分:2)
仍然是2步但没有循环
ary = ary.Select(str => str.Trim()).ToArray();
或
ary = ary.Split(',').Select(str => str.Trim())
.Where(str => str != string.Empty)
.ToArray();
保留RemoveEmptyEntries行为并删除可追踪的项目
答案 2 :(得分:2)
这非常巧妙地说:
//This could be inlined to the row below if you wanted
Regex oRE = new Regex(@"\s*\,\s*");
string TestString = ",, test , TEST 2 ,Test3";
//This is really the line you're looking for - the rest of the code just sets up an example
string[] Results = oRE.Split(TestString.Trim());
foreach(string S in Results){
Console.WriteLine(">>" + S + "<<");
}
作为一个单行:
string[] Results = new Regex(@"\s*\,\s*").Split(TestString.Trim());