2013-01-02 31 views
1

對不起,我正在更新該問題。 我寫,其接收按以下格式輸入的應用:解析Semi冒號將字符串分隔到通用列表<T>

someId = 00000-000-0000-000000; someotherId = 123456789; someIdentifier = 3030;

有沒有辦法,我可以將這些值添加到通用LIST<T>,讓我的列表包含以下

record.someid= 00000-000-0000-000000 
record.someotherId =123456789 
record.someIdentifier = 3030 

我很抱歉我在這個所以問這個問題新手。

+0

不半逗號? – Matthew

+0

謝謝你指出錯誤,我已經更新了這個問題。 – user1110790

回答

3

您可以使用Split獲得這似乎是key/value pair組合鍵和值對添加到您的Dictionary字符串的部分。

string str = "someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030"; 
string [] arr = str.Split(';'); 
Dictionary<string, string> dic = new Dictionary<string, string>(); 
for(int i=0; i < arr.Length; i++) 
{ 
     string []arrItem = arr[i].Split('='); 
     dic.Add(arrItem[0], arrItem[1]);    
} 

編輯基於由OP評論,添加到自定義類列表。

internal class InputMessage 
{ 
    public string RecordID { get; set;} 
    public string Data { get; set;} 
} 

string str = "someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030"; 
    string [] arr = str.Split(';'); 
List<InputMessage> inputMessages = new List<InputMessage>(); 
for(int i=0; i < arr.Length; i++) 
{ 
     string []arrItem = arr[i].Split('='); 
    inputMessages.Add(new InputMessage{ RecordID = arrItem[0], Data = arrItem[1]});   
} 
+0

更新了我的回答@LukeHennerley – Adil

7
var input = "someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030;" 
var list = input.Split(';').ToList(); 

已經添加到您的文件頭後:

using System.Linq; 
1

你需要知道什麼T將是一個List<T>在這種情況下,我會把它作爲一個字符串。如果你不確定使用object

List<object> objList = str.Split(new char[] { ';' }).ToList<object>(); 
+0

'String.Split'返回一個String數組('String []')。 –

+0

@Downvoter downvote的任何理由? – LukeHennerley

+0

我沒有downvote,但'列表'是不變的。 – Mir

1

如果格式總是如此嚴格,您可以使用string.Split。你可以創建一個Lookup

string str = "someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030;"; 
var idLookup = str.Split(new[]{';'}, StringSplitOptions.RemoveEmptyEntries) 
    .Select(token => new { 
     keyvalues=token.Split(new[]{'='}, StringSplitOptions.RemoveEmptyEntries) 
    }) 
    .ToLookup(x => x.keyvalues.First(), x => x.keyvalues.Last()); 

// now you can lookup a key to get it's value similar to a Dictionary but with duplicates allowed 
string someotherId = idLookup["someotherId"].First(); 

Demo

1

您可以從下面的代碼中使用:

 string str = "someId=00000-000-0000-000000;someotherId=123456789;someIdentifier=3030;"; 

     int Start, End = 0; 

     List<string> list = new List<string>(); 

     while (End < (str.Length - 1)) 
     { 
      Start = str.IndexOf('=', End) + 1; 
      End = str.IndexOf(';', Start); 

      list.Add(str.Substring(Start, End - Start)); 
     }