2017-08-25 42 views
1

在DataGridView中點擊過爭吵後,我把兩個單元格的值,在此行中:哪裏存儲兩個值進一步比較?

string id = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["Number"].Value); 
    string type = Convert.ToString(dataGridView1.Rows[e.RowIndex].Cells["dataGridViewTextBoxColumn46"].Value); 

因此,在這種結構來存儲這些值,也進一步起飛呢?

結果我需要比較id, type是否存在於結構中。我想試試Dictionary<int, int>。但是,很難以檢查是否有值在字典這樣的:Dictionary<'id', 'type'>

+0

可能解釋是正確的方法,那麼我應該使用'if(dict.ContainsKey(key)&& dict.ContainsValue(value)){...}'? – OPV

+0

'Tuple'或'ValueTuple'是你的朋友。 –

+0

它可以作爲數組 []的元組嗎? – OPV

回答

1

一個簡單的HashSet<Tuple<string, string>>可能會做:

  1. HashSet<T>是一組值提供O(1)平均查找時間「包含」查詢。

  2. Tuple<T1, T2>是表示一對值的一類,其使用值型平等的語義,即實現Equals和使用存儲在類內的值,這意味着用相同的構件的兩個不同實例將被認爲是相等的GetHashCode(和如果你想使用它們作爲HashSet<T>鍵,這是重要的

所以,你只會做這樣的事情:

// somewhere in your method or class 
HashSet<Tuple<string, string>> hashset = new HashSet<Tuple<string, string>>(); 

// once you get the (id, type) pair: 
hashset.Add(Tuple.Create(id, key)); 

// to check if the items are in the hashset: 
if (hashset.Contains(Tuple.Create("a", "b")) 
{ 
    // do stuff 
} 

// to remove the item from the hashset 
hashset.Remove(Tuple.Create("a", "b")); 
+0

如何檢查密鑰,值是否在Tuple?元組可以包含相同的對嗎?或者當只有一個值相同時?例如(1,2)和(1,3)? – OPV

+0

@OPV:'Tuple '是任意兩種類型的兩個值的集合。上述方法允許您檢查集合內是否已經存在特定的一組值'(x,y)'。如果您需要檢查是否存在任何值,則不需要'Tuple ',只需使用'HashSet '。另一方面,如果你需要分別檢查'id'和'key'的值,你會有兩個單獨的'HashSet '實例。 – Groo

+0

首先我可以添加:'a,b',然後'a,c'? – OPV