我想知道我是否可以转换它:
"abc , 123; xyz, 100; go, 9; move, 50;"
进入这个:
{ { "abc", "123" } , { "xyz" , "100" } , { "go" , "9" } , { "move" , "50" } }
(string[2]
数组)与一个长连接的LINQ
语句?
编辑:
最好是from-in-where-select
语句系列
编辑 2:
另外,有没有办法将输入字符串转换为某种复合类型,如struct { string, int }
数组或某些Tuple<string,int>
?
喜欢:
{
new Tuple<string, int>() { "abc", 123 } ,
new Tuple<string, int>() { "xyz" , 100 } ,
new Tuple<string, int>() { "go" , 9 } ,
new Tuple<string, int>() { "move" , 50 }
}
?
使用 String.Split
abd String.Trim
和 LINQ select
。
var result = (from keyValuePair in myString.Split(';')
where keyValuePair.Trim() != ""
select (from t in keyValuePair.Split(',')
select t.Trim()).ToArray()).ToArray();()
更新
要具有一系列KeyValuePair<string, int>
var result = (from keyValuePair in myString.Split(';')
where keyValuePair.Trim() != ""
let splittedKeyValuePair = keyValuePair.Split(',')
select new KeyValuePair<string, int>(splittedKeyValuePair[0].Trim(), int.Parse(splittedKeyValuePair[1]))).ToArray();
要有Dictionary<string, int>
var result = (from keyValuePair in myString.Split(';')
where keyValuePair.Trim() != ""
select keyValuePair.Split(',')).ToDictionary(kvp => kvp[0].Trim(), kvp => int.Parse(kvp[1]))
试试这个:
string str = "abc , 123; xyz, 100; go, 9; move, 50;";
stringses = str.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(new[] {','}))
.ToArray();