【发布时间】:2012-02-14 13:00:21
【问题描述】:
我有一个经常更改主题的数据库表。假设表中有 topic_id 和 topic。
在我的代码中,我需要计算每个主题中出现的次数。
有什么好的动态数组数据类型来存储每个主题的计数?
我应该使用 arrayList 吗?
如何使用它的示例会很有帮助。
【问题讨论】:
-
拥有计数后是否需要对其进行任何处理?您需要将计数存储在某处,还是只是根据需要即时计算?
我有一个经常更改主题的数据库表。假设表中有 topic_id 和 topic。
在我的代码中,我需要计算每个主题中出现的次数。
有什么好的动态数组数据类型来存储每个主题的计数?
我应该使用 arrayList 吗?
如何使用它的示例会很有帮助。
【问题讨论】:
正如其他答案所指出的那样,字典可能是一个不错的选择。
假设:
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);
}
【讨论】:
您可以使用dictionary <int,int>
【讨论】:
对于任何你有键值类型的数据并需要它的集合,地图(或字典)将是正确的选择。
【讨论】:
我会推荐一本字典
Dictionary<string, int> topicCounts
或者你可以多输入一点
Dictionary<Topic, int> topicCounts
然后您只需像索引器一样访问计数
【讨论】:
IDictionary<TKey, int> 的实现,其中 TKey 匹配您要查找的类型(可能是 Topic 可能是 int)。
对于大多数用途来说,最简单、最快的是Dictionary<int, int>。但是,由于这是 ASP.NET,并且您似乎将其用于某种缓存,您可能需要从多个线程访问此集合。 Dictionary 对多个并发读者来说是安全的,所以如果更新不频繁,那么用 ReaderWriterLockSlim 保护它可能是要走的路。如果您可以有多个线程同时尝试更新,那么您可能会从ConcurrentDictionary 或我自己的ThreadSafeDictionary 获得更好的性能。
【讨论】:
一个不错的选择是
Dictionary<int, int>
或者,如果您在多个线程中更新/阅读它,则非常棒
ConcurrentDictionary<TKey, TValue>
实际上,如果你喜欢 lambda,ConcurrentDictionary 有一个(自然是线程安全的)AddOrUpdate 方法,它在计算时会派上用场;如果没有在常规 Dictionary 中多次调用,想不出办法做到这一点。
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
【讨论】:
是的。 ArrayList 是最好的。
使用这个命名空间来包含 ArrayLists
using System.Collections;
声明一个数组列表,如
ArrayList myArray = new ArrayList();
将项目添加到数组列表。
myArray.Add("Value");
从数组列表中删除项目。
myArray.Remove("Value");
【讨论】:
List<System.Web.UI.Triplet> 可用于存储列表。
Triples 具有三个属性(First、Second、Third)——可以保存 TopicID、TopicName、Count。
或者您可以创建一个自定义类来保存您的 Topic 信息和 ID, Name, Count 属性。
【讨论】: