2014-02-18 80 views
0

我對使用字典還是比較新的,所以我需要一些幫助。在那一刻,我有以下字符串得到來自第三方設備裝入:動態添加到字典

26291,0.04760144554139385,18087,0.1990775029361712,41972,2.208226792687473, 26291,18087,41972,

什麼這是,兩個不同的價值觀發送。第一個和第二個數字(用逗號分隔)綁定到一個設備,第三個和第四個綁定到另一個設備,依此類推。偶數在每次更新時變化的奇數是常數。這些也被髮送到最先發送最小奇數的數組中。

在我的其他程序中,我需要將這些綁定到單個對象,而不管它們在數組中如何發送。我知道字典與關鍵價值一起工作,而上面的偶數就是完美的。

但是,我從來沒有創建一個動態的鍵和值的字典。有人可以告訴我這是如何在C#中完成的嗎?

在我之前做的事情是傳遞一個值並將其添加到另一個程序中的字符串數組中,並用逗號分隔它們。這種我想嘗試的新方式,有點超出了我的知識深度,所以如果有人能指引我正確的方向,我將不勝感激。

下面是我如何從我的iOS程序生成上面的字符串的代碼片段:

for (ESTBeacon *b in beacons) 
    { 
     NSString *currentBeaconDistance = [self sendBeaconDistanceToUnity:index WithBeacon:b FromBeacons:beacons]; 
     index++; 

     self.currentBeaconsString = [self.currentBeaconsString stringByAppendingString:currentBeaconDistance]; 
     self.currentBeaconsString = [self.currentBeaconsString stringByAppendingString:@","]; 


     NSString *beaconPower =[self sendBeaconMajorToUnity:index WithBeacon:b FromBeacons:beacons]; 
     index++; 

     self.beaconMajorString = [self.beaconMajorString stringByAppendingString:beaconPower]; 
     self.beaconMajorString = [self.beaconMajorString stringByAppendingString:@","]; 

     self.combinedString = [self.combinedString stringByAppendingString:beaconPower]; 
     self.combinedString = [self.combinedString stringByAppendingString:@","]; 
     self.combinedString = [self.combinedString stringByAppendingString:currentBeaconDistance]; 
     self.combinedString = [self.combinedString stringByAppendingString:@","]; 

    } 

,然後通過UnitySendMessage傳遞到統一。使用上述數據我在做以下幾點:

public void DistanceValue(string message) 
{ 

    fooString = message.Split (','); 

    if (fooString.Contains("-1")) 
    { 
     return; 
    } 

    distance_String = message; 
} 

上述方式讓我有被髮送任意數量的對象上,只要檢測到它們。示例字符串來自3個被檢測到的設備,但只要它們位於我的iPad的範圍內,它就可以很容易地顯示8個設備等。

+1

詞典要求'鍵'部分是不同的。如果您不能保證永遠不會有重複的密鑰,[Tuple]列表(http://msdn.microsoft.com/zh-cn/library/system.tuple%28v=vs.110%29 .aspx?cs-save-lang = 1&cs-lang = csharp#code-snippet-3)比Dictionary更適合:[存儲兩個值組合](http://stackoverflow.com/questions/21722146/store-a - 兩個值組合/)。 – har07

回答

2

你想拆就逗號,然後添加鍵值對爲Dictionary<string, string>

喜歡的東西:

string input = "26291,0.04760144554139385,18087,0.1990775029361712,41972,2.208226792687473, 26291,18087,41972,"; 

var d = new Dictionary<string, string>(); 

var split = input.Split(new char[] {','}); 

if (split.Count(x => x == ",") % 2 == 0) 
{ 
    throw new ArgumentException("Input is not key value pair."); 
} 

int i = 0; 
while (i <= split.Length) 
{ 
    try 
    { 
     d.Add(split[i], split[i + 1]); 

     ParseToDouble(numbers, split, i); 

     i = i + 2; 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex); 
    } 
} 

/// <summary> 
/// Attempts to Parse string to double. Adds to dictionary if successful. Does nothing if fails to parse. 
/// </summary> 
/// <param name="numbers">The dictionary of numbers</param> 
/// <param name="split">The raw input</param> 
/// <param name="i">The iterator</param> 
private static void ParseToDouble(Dictionary<double, double> numbers, string[] split, int i) 
{ 
    double key; 
    bool keySuccess = double.TryParse(split[i], out key); 

    double value; 
    bool valueSuccess = double.TryParse(split[i + 1], out value); 

    if (keySuccess && valueSuccess) 
    { 
     numbers.Add(key, value); 
    } 
} 

Dictionaries具有獨特的按鍵,所以你需要考慮你想要什麼如果您的輸入有重複的鍵,請執在你的例子中,密鑰"26291"被複制,所以不能再次添加到字典中。如果你要非唯一鍵,你需要

List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>() 

// Add 
list.Add(new KeyValuePair<string, string>("key", "value")); 

KeyValuePairKeyValue屬性是隻讀的。

+0

除非當然需要將字符串解析爲數字類型,否則值得向答案中加入 – Charleh

+0

@Charleh,完成。沒有真正的錯誤處理。 –

+0

具有相同關鍵字的元素已經存在於26291的字典中,它應該在您登錄異常時顯示,但它看起來像OP不知道這種行爲。 – Mateusz

2

可以使用正則表達式來單行解析成鍵 - 值對的字典:

var line = "26291,0.04760144554139385,18087,0.1990775029361712,41972,2.208226792687473,"; 
var regex = new Regex(@"(?<key>\d+),(?<value>\d+\.\d+),"); 
var dictionary = regex 
    .Matches(line) 
    .Cast<Match>() 
    .ToDictionary(
    match => match.Groups["key"].Value, 
    match => Double.Parse(match.Groups["value"].Value, CultureInfo.InvariantCulture) 
); 

字典然後包含以下數據:

 
Key | Value 
------+------------------- 
26291 | 0.0476014455413939 
18087 | 0.199077502936171 
41972 | 2.20822679268747 

我創建的普通用下面的假設表達:

  • 關鍵是一個非負整數
  • 的值與前和點
  • 鍵和值之間用逗號分隔和值也通過逗號終止之後

您可能有數字的非負的浮點數如果這些假設中的一些不正確,則稍微調整代碼。

+0

+ 1的正則表達式解決方案 –