2012-01-19 8 views
0

頻繁に変更されるトピックのデータベーステーブルがあります。テーブルにtopic_idとtopicがあるとします。.NETで優れた動的配列データ型を選択する

私のコードでは、各トピックで使用されているオカレンスの数をカウントする必要があります。

各トピックのカウントを格納するための優れた動的配列データ型とは何ですか?

arrayListを使用しますか?

使用方法の例が参考になります。あなたはデータのキーと値の並べ替えを持って、それの収集を必要とするものについてdictionary <int,int>

+0

あなたは一度それを持ってカウントで何かをする必要がありますか?カウントをどこかに保存する必要があるか、必要に応じて即座に計算していますか? –

答えて

2

他の回答で指摘されているように、おそらく辞書が良い選択でしょう。

仮定:

  • あなたtopic_idがintデータ型です。

使用例:TKeyは、あなたが(おそらくTopicおそらくint)にルックアップしますタイプと一致するIDictionary<TKey, int>

Dictionary<int, int> occurrencesOfTopicsByTopicID = new Dictionary<int, int>(); 

// The following code increments the number of occurrences of a specific topic, 
// identified by a variable named "idOfTopic", by one. 

int occurrences; 

// Try to get the current count of occurrences for this topic. 
// If this topic has not occurred previously, 
// then there might not be an entry in the dictionary. 
if (occurrencesOfTopicsByTopicID.TryGetValue(idOfTopic, out occurrences)) 
{ 
    // This topic already exists in the dictionary, 
    // so just update the associated occurrence count by one 
    occurrencesOfTopicsByTopicID[idOfTopic] = occurrences + 1; 
} 
else 
{ 
    // This is the first occurrence of this topic, 
    // so add a new entry to the dictionary with an occurrence count of one. 
    occurrencesOfTopicsByTopicID.Add(idOfTopic, 1); 
} 
1

、マップ(または辞書)が正しい選択になるだろう。

1

を使用することができます

1

私は辞書

Dictionary<string, int> topicCounts 

を示唆しているか、あなたが強く、もう少し

Dictionary<Topic, int> topicCounts 

それを入力することができ、あなただけのインデクサ

0

はいのような数にアクセスします。 ArrayListが最適です。

使用この名前空間を

using System.Collections; 

ArrayList myArray = new ArrayList(); 

ような配列リストは、ArrayListに項目を追加宣言のArrayListを含めます。

myArray.Add("Value"); 

arraylistからアイテムを削除します。あなたは、複数のスレッドでそれを読んで/優れた

ConcurrentDictionary<TKey, TValue> 

を更新している場合

myArray.Remove("Value"); 
+0

関連:http://stackoverflow.com/questions/725459/c-sharp-when-should-i-list-and-when-should-i-y-arraylist –

+0

なぜこれが最高だと思いますか?私はそれがすべての正しい選択ではないと思う – Pleun

+0

ArrayListは私が辞書を使用する個人的な意見の多くで最高ではない MethodMan

1

良い選択では、ラムダのような場合、実際に、ConcurrentDictionaryがあり

Dictionary<int, int> 

かだろうカウントを行うときに便利な、(自然にスレッドセーフな)AddOrUpdateメソッド。通常の辞書<>で複数の呼び出しなしでこれを行う方法を考えることはできません。

var dictionary = new ConcurrentDictionary<int, int>(); 

dictionary.AddOrUpdate(topic_id,   // For the topic with id topic_id 
         x => 1,   // Set count to 1 if it didn't already exist 
         (x, y) => y + 1); // Otherwise set to old value + 1 
0

List<System.Web.UI.Triplet>リストを格納するために使用できます。

Triplesには、TopicID、TopicName、Countを保持できる3つのプロパティ(First、Second、Third)があります。

Topicの情報をID, Name, Countのプロパティで保持するカスタムクラスを作成することもできます。

1

実装。

ほとんどの用途で最も簡単で最も速いのはDictionary<int, int>です。しかし、これはASP.NETなので、これをある種のキャッシュに使用しているようですが、おそらく複数のスレッドからこのコレクションにアクセスする必要があります。 Dictionaryは複数の同時読者にとって安全です。したがって、更新頻度が低い場合は、ReaderWriterLockSlimで保護するのがおそらく方法です。しかし、複数のスレッドを同時に更新しようとすると、ConcurrentDictionaryまたは私自身のThreadSafeDictionaryからより良いパフォーマンスを得ることができます。

関連する問題