2

我想知道我是否可以改变这个:

"abc , 123; xyz, 100; go, 9; move, 50;"

进入这个:

{ { "abc", "123" } , { "xyz" , "100" } , { "go" , "9" } , { "move" , "50" } }

(数组string[2])与一个长连接LINQ语句?

编辑:

首选from-in-where-select语句系列

编辑2:

另外,还有一种方法可以将输入字符串转换为某种复合类型,如 array ofstruct { string, int }或 some 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 }
}

?

4

2 回答 2

2

使用String.SplitabdString.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]))
于 2013-02-03T11:40:16.420 回答
1

试试这个:

string str = "abc , 123; xyz, 100; go, 9; move, 50;";

stringses = str.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(s => s.Split(new[] {','}))
               .ToArray();
于 2013-02-03T11:42:15.307 回答