我想知道我是否可以改变这一点:
"abc , 123; xyz, 100; go, 9; move, 50;"
进入这个:
{ { "abc", "123" } , { "xyz" , "100" } , { "go" , "9" } , { "move" , "50" } }
(string[2]
数组),带有一个长连接的LINQ
语句?
首选from-in-where-select
语句系列
另外,还有一种方法可以将输入字符串转换为某种复合类型,如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 }
}
答案 0 :(得分:2)
使用String.Split
和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]))
答案 1 :(得分:1)
试试这个:
string str = "abc , 123; xyz, 100; go, 9; move, 50;";
stringses = str.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
.Select(s => s.Split(new[] {','}))
.ToArray();