在.NET中选择一个好的动态数组数据类型
本文关键字:一个 动态 数据类型 数组 NET 选择 | 更新日期: 2023-09-27 18:21:03
我有一个经常更改的主题数据库表。假设表中有topic_id和主题。
在我的代码中,我需要统计每个主题中使用的出现次数。
什么是一个好的动态数组数据类型来存储每个主题的计数?
我应该使用arrayList吗?
举例说明如何使用它会很有帮助。
假设:
- 您的topic_id是
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>
对于任何有键值排序数据并需要其集合的数据,Map(或Dictionary)都是正确的选择。
我建议使用字典
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>
事实上,如果你喜欢lambdas,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有三个属性(第一、第二、第三),可以保存TopicID、TopicName和Count。
或者,您可以创建一个自定义类来保存具有ID, Name, Count
属性的Topic
信息。