2014-10-08 58 views
-1

我試圖更新&值添加到更新在一個ObservableCollection現有值

我已經定義了這樣的一個的ObservableCollection的ObservableCollection;

public ObservableCollection<Tuple<string, int>> LogSummary 
{ 
    get; 
    set; 
} 

以我類我訂閱發送含有字母的字符串的事件:A,B,C,d,E或F.

如果我接收到的字符串已經存在於集合我只想更新第二個項目(int),它是我收到的字符串字母的計數。

如果我寫這段代碼

LogSummary.Add(new Tuple<string, int>(_stringFromEvent, intValue)); 

在收集這隻會增加一個新的行,以便之前我用的是LogSummary.Add()我需要弄清楚如何檢查字符串是否已經存在,如果是這樣,它應該採用當前的int值並更新它,而不是向集合添加新行。

希望你明白我的問題! 由於提前, 傑克

回答

4
var existing = LogSummary.FirstOrDefault(t=>t.Item1 == _stringFromEvent) 
if(existing != null) 
{ 
    //update 
     LogSummary[LogSummary.IndexOf(existing)] = 
        new Tuple<string, int>(existing.Item1, intValue); 
} 
else 
{ 
    //insert new 
} 
+0

這工作,但我怎麼能只更新在LogSummary這int值? – hijack 2014-10-08 14:10:09

+0

@hijack,你可以使用'Tuple'的'.Item2'屬性來更新其他部分。請參閱上面的更新。 – 2014-10-08 14:12:29

+0

我收到「Property or indexer'System.Tuple .Item2'不能被分配給 - 它是隻讀的」但該屬性未設置爲私有。 – hijack 2014-10-08 14:15:21

相關問題